1.file讀檔案
讀取檔案的步驟:
1.打開檔案
2.檔案操作(讀或者寫、替換replace)
3.關閉檔案
例子:
import codecs
file1 = codecs.open("1.txt")
print(file1.read())
file1.close()
說明:codecs 導入子產品,解決檔案亂碼檔案的類
2.file寫檔案
寫檔案重要參數:
讀取:r
寫:w
二進制:b
追加:a
import codecs
file1 = codecs.open("1.txt","ab")
file1.write("This is the start\n")
file1.write("This is the end \n")
或者
file1.write("This is the {0}\n".format("start"))
file1.write("This is the %s\n" %"end")
3.file常用方法
readlines():讀取所有檔案,把檔案每行的内容,作為字元串的元素,放在list中
file1 = codecs.open("1.txt","rb")
print(file1.readlines())
readline():每次讀取一行
print(file1.readline())
next():讀取檔案下一行内容作為一個字元串
print(file1.next())
write():必須寫入一個字元串,和read()對應
writelines():必須寫入一個字元串清單,和readines()對應
list1 = ["a","b","c"]
file1 = codecs.open("example.txt","a")
file1.writelines(list1)
注:數字序列則報錯,需強制轉換類型,如str(i)
seek():定位光标移到某位置,例子中從光标位置開始寫會覆寫原來全部内容
file1 = codecs.open("1.txt","wb")
file1.seek(0)
file1.write("cc")
print(file1.tell())
其他的方法:
f.name 檢視檔案的名字
print f.closed 布爾值,判斷檔案是否關閉
print f.encoding() 檢視檔案的編碼
f.mode 檢視檔案的打開模式
flush():重新整理檔案緩存
4.file的with用法
with:将1.txt指派給f,再去操作f,這樣寫格式靈活,不需要考慮檔案關閉的情況
with codecs.open("1.txt","rb") as file1:
print(file1.read())
file1.close()
closed:判斷是否關閉
print(file1.closed)
print(file1.closed)
enumerate:列印行号
for line,value in enumerate(file1):
print(line,value)
linecache:從名為filename的檔案中得到全部内容,輸出為清單格式
import linecache
count = linecache.getline("1.txt",3)
print(count)
本文轉自 huangzp168 51CTO部落格,原文連結:http://blog.51cto.com/huangzp/1976937,如需轉載請自行聯系原作者