3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
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提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦