创建文件:
>>> file('test.txt','w') #如果文件不存在,以w形式打开会创建文件
<open file 'test.txt', mode 'w' at 0x7f1111597660>
#向文件中写入内容
>>> f=file('test.txt','w')
>>> f.write('Today is a good day')
#以只读方式打开文件
>>> f=file('rsc.txt','r')
>>> f.read() #读文件所有的内容
'Today is a good day\n'
遍历文件内容:
a=file('user_info.txt')
for line in a.readlines():
print line,
a.close()
追加内容:
f=file('test.txt','a')
f.write('append to the end')
f.close()
#关闭文件句柄
>>> f.close()
文件内容替换:
[root@node110 file]# cat message
rscpass
>>> import fileinput,tab
>>> for line in fileinput.input('message',inplace=1,backup='.bak'):
... line=line.replace('rscpass','gmy')
... print line,
[root@node110 file]# cat message
gmy
>>> help(fileinput.input)
input(files=None, inplace=0, backup='', bufsize=0,mode='r', openhook=None)
Return aninstance of the FileInput class, which can be iterated.
The parametersare passed to the constructor of the FileInput class.
The returnedinstance, in addition to being an iterator,
keeps globalstate for the functions of this module,.
inplace=0表示不将更改写入文件
inplace=1表示将更改写入文件
backup='.bak', 将源文件做一个备份,备份文件的后缀为.bak#message.bak
通过以下方法可以不关闭文件
>>> with open('test2.txt','r') as f:
... for i inf.readlines():
... print i
...
1111