我們常用open來開啟檔案
open(file, mode=『r』, buffering=-1, encoding=none, errors=none, newline=none, closefd=true, opener=none)
open file and return a stream. raise ioerror upon failure.
mode模式選擇
close() #關閉檔案
read(size=-1) #從檔案讀取size個字元,返回字串
readline() #從檔案中讀取一整行字串
write(str) # 將字串str寫入檔案
writelines(seq) #向檔案寫入字串序列seq,seq是乙個返回字串的可迭代物件
seek(offset,from) #移動檔案指標位置
tell() #返回當前檔案位置
import os
os.getcwd(
)#獲取當前目錄
os.chdir(
)#change dir
os.listdir(
)#列出當前目錄,返回列表
os.mkdir(
)#建立目錄,資料夾存在則丟擲異常
os.makedirs(
)#建立多級目錄
os.remove(
)#刪除檔案
os.rmdir(
)#刪除目錄
os.removedirs(
)#刪除多級目錄
os.system(
)#呼叫系統命令
os.path.isfile(
)#檔案是否存在
os.path.getsize(
)#返回檔案大小
#os.path 下有很多關於路徑常用的函式,可以通過dir(os.path)進行檢視
使用pickle儲存資料和文字
import pickle
list1 =
['dictionary.py'
,'fibonacci.py'
,'hanlot.py'
,'p1',5
,3.14
]pickle_file =
open
("newfile.pkl"
,"wb"
)pickle.dump(list1, pickle_file)
pickle_file.close(
)
再以二進位制的形式開啟
pickle_file2 =
open
("newfile.pkl"
,"rb"
)list3 = pickle.load(pickle_file2)
print
(list3)
Python學習筆記 四 檔案操作
讀取鍵盤輸入 buf raw input please input your name buf raw input 開啟檔案 如果hello.txt不存在 fp open hello.txt w w是說建立這個檔案,以寫的方式開啟 fp.write text fp.close 如果hello.txt...
Python學習筆記(四) 檔案讀取
教程 莫煩python 環境 pycharm 寫開啟 寫入內容 text this is a test.nthe second line nfinal line my file open myfile.txt a 以寫形式開啟檔案 my file.write text 往檔案裡寫內容 my file...
python 學習筆記2 檔案處理
1 檔案操作 1 檔案讀寫2 開啟,讀取,寫,關閉 4 f open cm r encoding utf 8 開啟檔案,預設gbk,所以需要轉碼5 f.close 一旦開啟必須關閉67 檔案開啟三種方式,讀 寫 追加 r w a8 讀 r 不指定時預設為讀9 讀寫 r 只要有r,檔案不存在都會報錯1...