1. 程式人生 > >【python】中open函式在遇到中文路徑的解決方法

【python】中open函式在遇到中文路徑的解決方法

# 儲存到檔案中
file_name = 'G:/pycode/mahongpengTest/biquge/dawangraoming/' + str(novel_chapter) + '.txt'

with open(file_name_utf8,'a') as f:
    f.write(novels)
    f.close()

報錯資訊如下

IOError: [Errno 22] invalid mode ('a') or filename

後來查詢問題原因又是因為中文編碼的問題

# 儲存到檔案中
file_name = 'G:/pycode/mahongpengTest/biquge/dawangraoming/'
+ str(novel_chapter) + '.txt' # 將中文編碼設定為 utf8 file_name_utf8 = unicode(file_name,'utf8') with open(file_name_utf8,'a') as f: f.write(novels) f.close()
  • 後來發現如果file_name 中有 ‘?’ 也會報錯,沒搞明白問什麼