0

I have been fumbling with this for a while, and I am thinking maybe there is no real way of doing this in python and the best approach is to always let the user figure out their absolute path and pass that in to my function and I can run it.

this code works if I run it from the directory that the code read_file.py is in. However, if I navigate one directory up cd .. and try to run python my_directory/read_file.py then it will fail and say file cannot be found.

Is there a way that I can pass in relative path and have it always work regardless of where I am in the terminal and am running this code. I come from a NodeJS and Java background.

Input

"""
read the a file from a path with both relative and absolute value to see which one works
the function accepts a path value instead of a str value
"""

import os
from pathlib import Path


def read_file_resolve(file_path: Path) -> None:
    file_path = file_path.resolve()

    with file_path.open() as f:
        print(f.read())


def read_file_os_absolute(file_path: Path) -> None:
    file_path = os.path.abspath(file_path)
    file_path = Path(file_path)

    with file_path.open() as f:
        print(f.read())


if __name__ == "__main__":
    my_file_path = Path("./upload_to_s3/my_downloaded_test.txt")

    # Get the absolute path to the file.
    # absolute_file_path = os.path.abspath(my_file_path)

    # Read the file.
    try:
        read_file_resolve(file_path=my_file_path)
        print("resolve worked")

    except Exception:
        read_file_os_absolute(file_path=my_file_path)
        print("os abs worked")

output:

FileNotFoundError: [Errno 2] No such file or directory

but when I run it from the directory that it is in, then it works fine

AugustusCaesar
  • 175
  • 2
  • 14

1 Answers1

2

__file__ is the path of the script itself.

Assuming your relative path is always relative to the script location, e.g.:

./my_directory
│   read_file.py
│
└───upload_to_s3
        my_downloaded_test.txt

Use:

my_file_path = Path(__file__).parent / 'upload_to_s3' / 'my_downloaded_test.txt'

Then the current directory won't matter.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251