Python處理檔案

2021-08-19 16:36:48 字數 1966 閱讀 9309

檔案開啟方法:open(name[,mode[buf]]),name為檔名,mode為讀取方式,buf為讀取緩衝大小

檔案讀取方式:read([size]),讀取指定長度,如果size不存在,則讀取全部

readline([size]),讀取一行中size長度

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

iter:使用迭代器完成檔案讀取操作

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

writelines(sequences_of_strings),寫多行到檔案

mode(讀取方式):

r,唯讀方式開啟,檔案必須存在

w,只寫方式開啟,檔案不存在則建立,檔案存在則清空檔案內容

a,追加方式開啟,檔案不存在則建立

r+/w+,讀寫方式開啟

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

rb,wb,ab,rb+,wb+,ab+ 以二進位制方式開啟

示例:test.txt的內容為 12345678

open('text.txt','r'):只能讀,不能寫

open('text.txt','w'):開啟後內容變為空,再寫入 abc,結果為 abc

open('text.txt','a'):開啟後寫入  abc ,結果為 12345678abc

open('text.txt','r+'):開啟後寫入  abc ,結果為 abc45678

open('text.txt','w+')同open('text.txt','w')

readline(size): 當前行剩餘長度》size,返回當指定長度;否則返回當前行剩餘內容

readlines(size): 讀取到size長度,返回乙個列表,每一行作為乙個資料項,且最後指標所在行會全部讀取

示例:檔案為 12\n12\n12\n,當size為4時,會返回['12\n','12\n']

iter: 可以把檔案變為迭代物件,一行一行遍歷

f = open("...")

iter_f = iter(f)

for line in iter_f:

print(line)

f.close()

寫操作時,由於有寫快取機制,執行write後,需要關閉檔案或呼叫flush函式,內容才會真正寫入到檔案;當寫入量大於等於快取空間時,寫快取會自動同步到磁碟檔案中

f.close()或者f.flush()

檔案指標移動:f.seek(...)

seek(offset[,whence]),offset為偏移量,可以為負數但當前位置加上偏移量不能超出檔案範圍,whence為偏移相對位置

whence:os.seek_set   相對檔案起始位置,0

os.seek_sur  相對於當前位置,1

os.seek_end  相對於檔案結尾位置,2

f.tell()返回當前指標所在的位置

檔案屬性:

file.fileno() 檔案描述符

file.mode 檔案開啟許可權

file.encoding 檔案編碼格式

file.closed 檔案是否關閉

ini配置檔案:

需要匯入 configparser

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...