Home > Software engineering >  How do I open a text file from a parent directory in Python?
How do I open a text file from a parent directory in Python?

Time:12-15

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'

CodePudding user response:

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')

CodePudding user response:

You can either use the absolute path:

file = open('/home/user/Project/Source/Documents/hello.txt

Change the directory names upstream of Project to what you have set up.

Or if second.py is not going to move you can use relative path:

file = open('../Documents/hello.txt')

The '..' takes you to the parent directory and you can then drop down to Documents directory from there. You can also stack the '..'. For example you can get to main.py by using:

file = open('../../main.py')

  • Related