Python檔案處理

2021-08-17 04:54:43 字數 548 閱讀 7040

1.檔案開啟:open(檔案路徑,[開啟方式],[緩衝buffering大小])

開啟方式:預設—— 唯讀

'r'——唯讀,檔案必須存在

'w'——只寫,檔案不存在則建立檔案,檔案存在則清空原檔案內容

'a'——追加方式,檔案不存在則建立檔案

'r+'——讀寫方式開啟

'w+'——同w

'a+'追加和讀寫方式開啟

'rb','wb','ab','rb+','wb+','ab+'二進位制方式開啟,常用於

2.檔案寫入:

write(str):將字串寫入檔案

writelines(sequence_of_strings):寫多行到檔案

3.檔案讀取:

read([size]):讀取size個位元組,預設全部讀取

readline([size]):讀取一行

readlines([size]):讀取完檔案,返回每一行所組成的列表

讀取完內容後再進行讀取時顯示 ' ' ,在操作時需要關閉,重新開啟檔案

4.檔案關閉

close()

python檔案處理

def cal input input.txt output output.txt cal方法為主程式,推薦這樣做而不是python.exe xx.py 預設引數為python目錄的兩個txt,如為其他檔案自己指定。infile file input,r 開啟源資料檔案 outfile file o...

python 檔案處理

1.開啟檔案 open a.txt 當前目錄下的a.txt open root a.txt 開啟某個目錄下的檔案 2.按行顯示檔案 a open a.txt a.readline ni hao n a.readline wo xianzai hen xiang ni n a.readline ni ...

Python檔案處理

open name mode buf read size readline size readlines size 這裡的size是指,io定義的default buffer size為單位大小 iter 迭代器迭代每行 write str writelines sequwence of strin...