FileNotFoundError Appears Even though the File Exists

Asked 2 years ago, Updated 2 years ago, 39 views

FileNotFoundError appears.
Visit views.py to

f=open('test.txt','r')
f.close()

I wrote.When you run this code,

FileNotFoundError: [Errno2] No such file or directory: 'test.txt'

received an error.
However, there is test.txt in the same hierarchy as views.py and I don't know why FileNotFoundError appears.Changing 'test.txt' to './test.txt' results in the same error.
Why do I get an error?How can I fix the error?

python python3

2022-09-30 20:13

2 Answers

If test.txt exists successfully, views.py appears to be running from a directory other than where views.py is located.

#!/usr/bin/env python3
from os import chdir

chdir("/path/to/")#views.py's directory
f = open ('test.txt', 'r')
f.close()

exit(0)

You can use chdir to specify the directory to run open.

Of course, you can specify the full path of test.txt for open as shown in Answer of Wow.


2022-09-30 20:13

The filename must be specified in the full path

test.txt is in the same hierarchy as views.py and

The current directory is not in the source file location


2022-09-30 20:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.