Skip to content

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

Last Updated on 2021-10-12 by Clay

This is a common error when you using Python to develop, almost everyone who learns python has encountered it.

The complete error message is as follows:

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'


According to the error message, we can see the reason for this error is that we want to use python to access a file or folder, but the path we provided does not have this file or folder.


Problem recurrence

This is a sample code that repeat the error.

There is no syntax error, but the file cannot be found through the file path.

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'



Solution

As explained earlier, there is no problem with the syntax of the program. So the only thing we can do is to check if the path is wrong or the file name is misspelled.

After the correction, the file can probably be read.


References


Tags:

Leave a ReplyCancel reply

Exit mobile version