針對1.txt檔案進行操作
#導入codecs子產品,此子產品可以解決Python讀取檔案編碼的問題
例子1
import codecs
#打開1.txt檔案
f = codecs.open('1.txt')
text = f.read()
#使用replace方法将text字元串中的a替換為1
a = text.replace('a','1')
print (f.read())
print a
#關閉檔案
例子2
f.close()
f = codecs.open('2.txt','w')
f.write('This is a TEST file!')
f.close
replace()方法可以針對讀取的檔案進行替換操作
open(‘filename’,mode)讀取檔案
mode 參數為r讀 w寫 b二進制讀取 a追加寫入
readline()方法是讀取檔案的一行
f.redline()
next()方法為讀取打開檔案光标的下一行
f.next()
readlines()方法可将檔案内容讀取為一個清單,檔案中的行就是清單中的元素,程式中第二次使用readlines方法的時候會從第一次讀取的末尾繼續讀取
#codecs.open()預設mode為rb,是以讀取為二進制
f = codecs.open('2.txt')
print f.readlines()
輸出:['This is a TEST file!\r\n', '1\r\n', '2\r\n', '3']
write()和writelines()方法是寫入檔案,writelines需要傳一個清單
f = codecs.open('2.txt','wb')
f.write('abc\n def\n')
f.writelines(['1\n','2\n','3\n'])
tell()方法可以輸出調用之前有多少個字元
seek()方法可以移動在檔案中的光标,seek(0)是移動到最前,移動光标後則從0字元開始替換之前内容
f.write('abc\ndef\n')
print f.tell()
f.seek(0)
f.write('hhh')
#檢視檔案名稱
print f.name
#檢視檔案的打開mode方式
print f.mode
#重新整理檔案到緩存中
print f.flush()
#檢視檔案的編碼格式,未指定輸出None
print f.encoding
檔案中with語句的用法
with codecs.open('1.txt') as ff:
print ff
例子1 輸出檔案的第幾行内容
#linecache.getlines('a.txt')Python中已有的方法,可以檢視源碼學習
for line,num in enumerate(ff):
if line == 3-1: