1 read(讀),write(覆蓋寫),add(追加)
f = open('檔名',mode = '
r',encoding= '
utf-8
')#第乙個引數是要操作的檔案的名字
#第二個引數選擇的模式'r''w''a'等
#第三個引數自定義的編碼集
read(讀):唯讀 不進行其他操作.
f = open('tt',mode 1= '
r',encoding= '
utf-8
') #
對檔案tt進行讀操作,不能進行其他操作
f.read()
write(寫):覆蓋寫,不進行其他操作.寫之前會先清空檔案的內容,檔案不存在的時候會建立乙個檔案
f =open('tt',mode='
w',encoding='
utf-8
') #
清空完檔案tt的內容,然後再寫進去
f.write('寫的內容')
add(追加寫):在檔案內容的末尾進行追加內容
f= open('tt',mode='
a',encoding='
utf-8
') #
在tt檔案的內容中追加內容
f.write('追加的內容')
將乙個檔案進行備份操作:
with open('tt',mode="
r",encoding='
utf-8
') as f:
msg =f.read()
with open('nn
',mode='
a',encoding='
utf-8
')as f1:
f1.write(msg)
2,r+(讀,寫),w+(寫,讀),a+(追加寫,讀)
2.1 r+ 讀 寫
mode = r+時,必須進行先讀後寫操作,不然檔案會被錯誤改動
2.2 w+ 寫 讀
mode = w+時,寫讀的時候,必須移動游標seek(0),才能完整讀出內容
2.3 a+ 追加寫 讀
mode =a+時,寫讀的時候,必須移動游標seek(0),才能完整讀出內容
3.其他操作
f = open('tt',mode= '
r',encoding='
utf-8
')#必須需要結束
f.close()
with open('tt
',mode='
r',encoding='
utf-8
') as f: #不需要結束
seek() 移動游標
引數為位元組數
雙個數字為see(0,0) 檔案開頭位置
雙個數字為see(0,1) 檔案當前位置
雙個數字為see(0,2) 檔案結尾位置
Python中對 檔案 的各種騷操作
python中對檔案 資料夾 檔案操作函式 的操作需要涉及到os模組和shutil模組。得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 返回指定目錄下的所有檔案和目錄名 os.listdir 函式用來刪除乙個檔案 os.remove 刪除多個目錄 os.removedi...
對檔案的操作
win32 shfileoperation 1.將 c test.txt 拷貝到 d shfileopstruct lpsh zeromemory lpsh,sizeof lpsh lpsh.hwnd hwnd desktop lpsh.fflags fof noconfirmation fof p...
對檔案的操作
對檔案的操作大致分為3類 第一類為r 唯讀 當進行唯讀操作時,無法對文字進行更改。注意 當進行r操作時游標會移至最前方從而讀取游標後的內容。第二類為w 只寫 當進行只寫操作時,無法對檔案進行讀取操作。注意 當進行只寫操作時會情況檔案裡的內容。第三類為a 只追加 當進行只追加操作時,無法讀取內容。注意...