Python基礎文章集合請移步骄瓣。
文件操作
文件操作,無外乎讀寫师坎,但首先你要打開文件恕酸。
打開文件
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
讀取所有內(nèi)容
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()
遍歷文件數(shù)據(jù)
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