search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

python with open 寫入與讀取檔案的精簡教學 - Python 教學筆記本









with open read 讀取檔案

這裡有幾點要注意 :

"file_name.txt" 指的是當前目錄下的資料,所以是"相對路徑"的概念,如果要指定打開其他檔案夾的話,要以" 絕對路徑 "的寫法

encoding="utf8" 指的是編碼格式,一般網頁上抓下來的檔案通常是以 "utf-8" 編碼格式

errors='ignore' 指的是忽略特殊字元的設定,避免在讀檔時發生意料之外的狀況


with open("file_name.txt", "r",encoding="utf-8",errors='ignore') as f: print(f.read())

with open write 寫入檔案

with open('test.txt', 'w',encoding="utf8",errors='ignore') as f: f.write('Hello, world!')

with open write json 檔案

result = {"apple":"25$"} with open("result.json","w",encoding="utf-8") as f: json_file = json.dumps(result) f.write(json_file)


如果遇見檔案內有其他字串或符號想取代成別文字或符號的時候該怎麼處理呢?
這時候就需要用到 " replace( ) " 這個內建函數了,大家可以參考以下寫法來解決這個問題

判斷並取代成別的string

def Judge(): with open("test.txt",encoding="utf8") as f: s = f.read() if "'" in f : return None with open("test.txt", "w",encoding="utf8",errors='ignore') as f: new_file = s.replace("'", '"') # 可以寫成 replace("\'", "\"") f.write(new_file) if __name__ == "__main__": Judge()


熱門推薦

本文由 python-learnnotebookblogspotcom 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦