文件操作
文件操作,无外乎读写,但首先你要打开文件。
打开文件
f = open(filename, mode)
filename是文件名,可以带目录;mode是读写模式(可以是读,写,追加等);f是file handler。
关闭文件
f.close()
模式
- “r”: Open a file for read only
- “w”: Open a file for writing. If file already exists its data will be cleared before opening. Otherwise new file will be created
- “a”: Opens a file in append mode i.e to write a data to the end of the file
- “wb”: Open a file to write in binary mode
- “rb”: Open a file to read in binary mode
写入文件
注意,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 file
读取所有内容
f = 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()
Append
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