Python 讀取TXT檔案

2021-07-26 19:02:31 字數 1589 閱讀 9052

一、開啟檔案

f = open(filename,access_mode='r',buffering=-1)
filename:檔名

access_mode:開啟方式,r讀,w寫,a追加,r+ w+ a+ 都是以讀寫方式開啟,rb二進位制讀,wb二進位制寫,rb+ wb+ ab+二進位制讀寫

buffering:預設值

二、對檔案進行操作

將檔案中的內容讀入到乙個字串變數/列表中

函式:read(),readline(),readlines(),write(),writelines()

1、read() 讀取整個檔案到字串變數中

2、readline() 讀取檔案中的一行,然後返回整行,包括行結束符到字串變數中

3、readlines() 讀取整個檔案,返回乙個字串列表,列表中的每個元素都是乙個字串,代表一行

fp=open('filename.txt')

lines = fp.readlines()

for line in lines:

...fp.close()

######更高效的實現方式########

fp = open('filename.txt')

for line in fp:

...fp.close()

4、write() 將字串輸出到檔案中

f = open('filename,txt','w')

f.write('welcome to my house')

f.close()

########

f = open('filename,txt','w')

f.write('welcome\nto\nmy\nhouse')

f.close()

5、writelines() 將字串列表寫入檔案,行結束符並不會自動被加入,需要手動在每行的結尾加入行結束符。

f = open('filename,txt','w')

w = ['hello', 'world']

f.writelines(w)

f.close()

###########

f = open('filename,txt','w')

w = ['hello\n', 'world']

f.writelines(w)

f.close()

################

f = open('filename,txt','w')

f.write('firstline\n')

f.write('secondline\n')

f.write('thirdline\n')

f.close()

6、seek() 移動檔案讀取指標到指定的位置

f.seek(p,0) 移動當檔案第p個位元組處,絕對位置

f.seek(p,1) 移動到相對於當前位置之後的p個位元組

f.seek(p,2) 移動到相對文章尾之後的p個位元組

7、tell() 返回檔案指標的位置

python 讀取txt檔案

txt檔案內容 1.全部讀取 file open e others 測試.txt r 開啟檔案 f all file.read 讀取所有檔案內容 print f all file.close 關閉檔案結果 2.按行讀取 file open e others 測試.txt r 開啟檔案 for lin...

python 讀取txt 檔案

filename users sr00117 desktop bom1.txt txt檔案和當前指令碼在同一目錄下,所以不用寫具體路徑 def readtxt valuelist all list alone list with open filename,r as file to read for...

Python 讀取txt檔案

f.read 把整個文件當成乙個字串,n 也算作乙個字元,可以用f.read 3 來獲取第3個字元 f.readline 只讀取當前行,把當前行看作乙個字串,n 也算作乙個字元 f.readlines 把整個文件看成乙個字串列表,每一行是列表中的元素,為字串 保證無論是否出錯都能正確地關閉檔案 wi...