-
創(chuàng)建文件
f = file('myfile.txt','w')
f.write('hello,baby!')
f.close()
w :寫(如果已經(jīng)存在,會(huì)將其覆蓋)
r :讀
a :追加
w+、a+、r+:讀寫模式,以文本方式讀
wb、rb :讀寫模式, 以二進(jìn)制方式讀
import time
f = file(‘test.txt’,'w') // 與open(‘test.txt’,'w')沒有差別
for i in range(10):
time.sleep(1)
f.write(the %s loops\n'%i)
f.flush()
f.close
-
遍歷文件內(nèi)容
a =file ('user_info.txt')
for line in a.readlines():
print line
a.close
-
追加
f = file("text.txt",'a')
f.write("append to the end")
f.colse()
-
文件內(nèi)容替換
for line in fileinput.input("filepath",inplace = 1,backeup = ".old"):
line = line.replace("oldtext","newtext")
print line
inplace = 1 替換的內(nèi)容寫會(huì)原文件,inplace = 0,如果只打印出來,不寫到原文件。
backeup = ".old" 做一個(gè)備份。
-
文件操作函數(shù)
file.read() 讀取全部文本
file.tell() 返回文件位置 字符數(shù)
file.seek(number) 回溯到number 數(shù)字符數(shù)處
file.truncate(number) 從當(dāng)前處截?cái)嗟絥umber字符處
import tab
with open("filepath","r+") as f: 相當(dāng)于f = open("filepath","r+") ,但是它會(huì)自動(dòng)關(guān)閉文件句柄。