python知识整理(读写文件)_4

核能气质少年 提交于 2020-04-06 19:55:42

!#/usr/bin/python env
# -- conding --

awk -F ':'  '/OO/'  password
awk -F ':'  '$1~/root/'   password

读写文件:  
1、新建一个文件,并写入内容,文件不存在会自动创建。

test = 'This is my first file\n Thsi is line'

file=oepn('2.txt','w')                //w 如果文件不存自动创建。
file.write(test)
file.close()

file.read()           查看这个文件:

如何给文件增加内容:
file_append='\n this  is  file append'
file=open('2.txt','a')
file.write(test)
file.close()

掌握append的用法:   file=open('2.txt','a')     打开类型为 a     a 则表示 append

3、读取文件内容:
file=open('2.txt','r')
content=file.read()
print(content)

按行读取:
如果想在文档中一行一行的读取,比如excel文件:
读取的内容和你使用的次数有关,如 使用第二次的时候,读取的就是文本你的第二行:
存取到了一个 python list 里面:

file = open('2.txt','r')
content = file.readline()
second_read_time = file.readline()
print(contend,second_read_time)

输出所有行:     file.readline
 list 形式

file = open('2.txt','r')
content = file.readlines()
print(content)

附加:
如何只要求输出指定的行:    比如只要第三行:
import   linecache
text = linecache.getline('2.txt',3)
print(text)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!