Python 基礎之檔案
阿新 • • 發佈:2018-12-26
檔案操作一般需要三個步驟,開啟檔案(open)、寫或讀(read、write)、關閉檔案。
開啟檔案
f = open("檔名", "開啟方式", [encoding = "utf-8"])
- 開啟方式一般有:r、w、a、rb、wb、ab、r+、w+、a+
寫入或讀檔案
f.write("想寫入的內容") # 寫檔案
或者
f.read() # 讀檔案
關閉檔案
f.close()
列印檔案內容
for line in f:
print(line)
例項
- 建立一個檔案,起名 " yesterday_once_more.txt ",內容如下:
When I was young
(當我小時候)
I'd listen to the radio
(聆聽收音機)
Waiting for my favorite songs
(等待著我最喜歡的歌曲)
When they played I'd sing along
(當歌曲播放時我和著它輕輕吟唱)
It made me smile
(我臉上洋溢著幸福的微笑)
- 建立一個 .py 檔案,進行檔案修改,並存到新檔案 " today.txt " 中:
f = open("yesterday_once_more.txt", "r", encoding="utf-8") f_new = open("today.txt", "w", encoding="utf-8") for line in f: if "當歌曲播放時我和著它輕輕吟唱" in line: line = line.replace("當歌曲播放時我和著它輕輕吟唱", "和著它輕輕吟唱") f_new.write(line) f.close() f_new.close()