檔案的開啟:
《變數名》=open(《檔名》,《開啟模式》)
檔名:檔案路徑和名稱(原始檔同目錄可省路徑)
檔案的開啟模式:
'r'唯讀模式,預設值,如果檔案不存在,返回filenotfounderror
'w'覆蓋寫模式,檔案不存在則建立,存在則完全覆蓋
'x'建立寫模式,檔案不存在則建立,存在則返回fileexistserror
'a'追加寫模式,檔案不存在則建立,存在則在檔案最後追加內容
'b'二進位制檔案模式
't'文字檔案模式,預設值
'+'與r/w/x/a一同使用,在原功能基礎上增加同時讀寫功能
檔案的關閉:
《變數名》.close()
檔案的寫入:
.write(s) 向檔案寫入乙個字串或位元組流
>>>f.write("中國是個偉大的國家")
.writelines(lines) 將乙個元素全為字串的列表拼接寫入檔案
>>>ls=["中國","法國","美國"]
>>>f.writelines(ls)
中國法國美國
.seek(offset) 改變當前檔案操作指標的位置,offset含義如下:0 - 檔案開頭; 1 - 當前位置;2 - 檔案結尾
>>>f.seek(0) #回到檔案開頭
python學習 檔案的操作
with關鍵字來幫我們管理上下文 with open a.txt w as f pass with open a.txt r as read f,open b.txt w as write f data read f.read write f.write data 檔案的操作流程 1.開啟檔案,得到...
Python學習 檔案操作
python使用open來開啟資料流 data open data.txt 下面是乙個讀取乙個檔案,然後逐行輸出的 try data open data.txt for each line in data try role,line spoken each line.split 1 print ro...
Python學習(檔案讀寫)
一 用os.makedirs 建立新資料夾 在桌面上建立乙個名稱為1的資料夾。import os os.makedirs c users king desktop 1 二 檢視檔案大小和資料夾內容 1.os.path.getsize path 返回path 引數中檔案的位元組數。import os ...