文件操作,无外乎读写,但首先你要打开文件。
f = open(filename, mode)
filename是文件名,可以带目录;mode是读写模式(可以是读,写,追加等);f是file handler。
f.close()
注意,write
不会自动加入\n
,这一点不像print
。
f = open('myfile.txt', 'w') # open file for writing
f.write('this is first line\n') # write a line to the file
f.write('this is second line\n') # write one more line
f.close()
总共有三个模式:
read([number])
: Return specified number of characters from the file. if omitted it will read the entire contents of the file.readline()
: Return the next line of the file.readlines()
: Read all the lines as a list of strings in the filef = open('myfile.txt', 'r')
f.read()
'this is first line\nthis is second line\n'
f.close()
f = open('myfile.txt','r')
f.readlines()
['this is first line\n', 'this is second line\n']
f.close()
f = open('myfile.txt','r')
f.readline()
'this is first line\n'
f.close()
f = open('myfile.txt','a')
f.write('this is third line\n')
f.close()
f = open('myfile.txt','r')
for line in f:
print line,
this is first line
this is second line
this is third line
f.close()
with open
with open('myfile.txt','r') as f:
for line in f:
print line,
this first line
this second line
this is third line
with open('myfile.txt','r') as f:
for line in f.readlines():
print line,
this is first line
this is second line
this is third line