Skip to content
Advertisement

Import a single file from another directory

I’m kind of new with python and there is something troubling me. I’m using pandas to read an excel file. All works well if I have the excel in the same directory as my .py file.

What I want to know is what is the best way to get a file that is in a completely different path. I’ve searched a lot and haven’t found a straightforward answer. I’ve seen examples with sys.append, examples with external libraries, etc. I am trying to understand the pros/cons as well of each solution. Ideally I would like to have the file path as a user input

Advertisement

Answer

sys.path is where Python tries to locate modules or packages to import them. Not files when you are trying to access them. (like your excel file)

On the other hand, open built-in function or Pandas read functions require a path to a file. As long as you work with absolute paths you don’t need to worry about it.

If you want to give it a relative path, first check to see where you are and then locate your file relative to your working directory.

with os.getcwd() you can get your current working directory.

As an example, suppose we have:

tmp/
└── inside_directory
    ├── pfile.py
    └── text.txt

If my terminal indicates that I’m in tmp directory and I run my pfile.py with:

python inside_directory/pfile.py

and the content of pfile.py be:

with open("text.txt") as f:
    print(f.read())

I will get error which says: FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'.

Why? because I used relative path and there is no text.txt in the tmp directory.

Then what are the solutions?

Option-1: use open("inside_directory/text.txt") instead of open("text.txt").

Option-2: first go to inside_directory then use open("text.txt") and run your script with python pfile.py.

Option-3: Use absolute path. You can access that file regardless of where you are now.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement