I am trying to open a text file from a parent directory in Python. Here is the tree (simplified):
+ Project:
- main.py
+ Source:
+ Documents:
- hello.txt
+ Modules:
- second.py
I am trying to read hello.txt
from second.py
.
Here is the problem line in second.py
:
file = open('../Documents/hello.txt', 'r')
Returns Error: FileNotFoundError: [Errno 2] No such file or directory: '../Documents/hello.txt'
Relative paths are relative to the working directory. If you are running your code in the Projects
directory, the path needs to be relative to that directory, so you need to open('./Source/Documents/hello.txt')