Search code examples
pythonmodulefilepathprogram-entry-point

How to read a file contained in same module as __main__.py from outside the module?


Here is my file tree:

foo  
|-- bar  
|-- |-- __main__.py  
`-- `-- some_file.txt  

Here's __main__.py:

with open('some_file.txt', 'r') as f:
    print(f.read())

When the current working directory is bar/ and I run

$ python __main__.py

the result is to print whatever content is in some_file.txt to console.

When I change the current working directory to foo/ and run

$ python bar/

I get this:

Traceback (most recent call last):
  File "/data/data/com.termux/files/home/foo/bar/__main__.py", line 1, in <module>
    with open('some_file.txt', 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'some_file.txt'

How do I fix this?


Solution

  • You can get the path to the script with __file__. Thus you can write your code as:

    from pathlib import Path
    here = Path(__file__)
    with (here/"some_file.txt").open() as f:
        print(f.read())
    

    I've used pathlib to avoid cross platform problems with path concatenation: else use os.path.join.