python操作檔案存在的問題解決辦法
python操作檔案存在的問題解決辦法
1、在學習從檔案讀取資料中,寫了個示例程式碼,讀取不在同一個目錄的file.txt,執行後報這個Python OSError: [Errno 22] Invalid argument:錯誤: (1)、首先,在F盤的python_stu中新增了一個file.txt,同時在F盤的python_stu檔案目錄底下新增一個file資料夾,裡面有個file_reader.py來讀取python_stu檔案目錄底下的file.txt,程式碼分別如下: file.txt: 測試 測試2 測試3 file_reader.py: with open('F:\python_stu\file.txt') as file_obj: contents = file_obj.read(); print(contents.rstrip()); (2)、執行後報錯: (3)、出現這種錯誤的原因是由於讀取不到這個檔案,看Traceback報的錯誤,最後一行,很明顯讀取不到file.txt,前面的F:\\python_stu沒錯,後面的名稱怎麼變了,還是x0cile.txt。 (4)、解決辦法,可修改上述第一行程式碼為: with open('F:\python_stu/file.txt') as file_obj: 或者: with open('F:/python_stu/file.txt') as file_obj: 或者: with open('F://python_stu//file.txt') as file_obj: 又或者: with open('F:\\python_stu\\file.txt') as file_obj: 還有一些我就不附上了,上面第一種方式不統一,最好不要用,用統一的方式,而且有時候還有注意一些轉義字元,比如 \t,\n也會導致報錯。posted on 2019-05-14 23:04鴻雁 閱讀(1)編輯 收藏 所屬分類:IT技術相關