Skip to content

[已解決][Python] FileNotFoundError: [Errno 2] No such file or directory: ‘xxx.txt’

這是一個在 Python 開發中最常遇到的錯誤之一,相信每個學習 Python 的人都曾經遇到過。

通常完整的錯誤訊息如下:

Traceback (most recent call last):
  File "/Users/clay/Projects/PythonProjects/python_children_edu/test.py", line 1, in <module>
    open("data.txt", 'r', encoding="utf-8").read(
FileNotFoundError: [Errno 2] No such file or directory: 'xxx.txt'


根據錯誤訊息所提供的資訊,我們可以看出這個錯誤發生的原因,是因為我們想要使用 Python 存取一份檔案或是資料夾,但是我們所提供的路徑並沒有這份檔案或資料夾。


問題復現

以下是一段重複這個錯誤的範例程式碼,在語法上並沒有什麼錯誤,只是單純地無法透過我們所提供的檔案路徑找到該檔案。

open("data.txt", 'r', encoding="utf-8").read()


Output:

Traceback (most recent call last):
  File "/Users/clay/Projects/PythonProjects/python_children_edu/test.py", line 1, in <module>
    open("data.txt", 'r', encoding="utf-8").read(
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'



解決方法

剛才已經說明了,在程式語法上並沒有問題。所以我們唯一能做的,就是好好地去檢查是不是搞錯了路徑、或拼錯了檔案名稱

修正之後,多半便可以讀取檔案內容了。


References


Tags:

Leave a Reply