Open File in a Relative Location in Python

Reading file using relative path in python project

Relative paths are relative to current working directory.
If you do not your want your path to be, it must be absolute.

But there is an often used trick to build an absolute path from current script: use its __file__ special attribute:

from pathlib import Path

path = Path(__file__).parent / "../data/test.csv"
with path.open() as f:
test = list(csv.reader(f))

This requires python 3.4+ (for the pathlib module).

If you still need to support older versions, you can get the same result with:

import csv
import os.path

my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
test = list(csv.reader(f))

[2020 edit: python3.4+ should now be the norm, so I moved the pathlib version inspired by jpyams' comment first]

Relative paths in Python

In the file that has the script, you want to do something like this:

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its package resources API instead.

UPDATE: I'm responding to a comment here so I can paste a code sample. :-)

Am I correct in thinking that __file__ is not always available (e.g. when you run the file directly rather than importing it)?

I'm assuming you mean the __main__ script when you mention running the file directly. If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7):

#foo.py
import os
print os.getcwd()
print __file__

#in the interactive interpreter
>>> import foo
/Users/jason
foo.py

#and finally, at the shell:
~ % python foo.py
/Users/jason
foo.py

However, I do know that there are some quirks with __file__ on C extensions. For example, I can do this on my Mac:

>>> import collections #note that collections is a C extension in Python 2.5
>>> collections.__file__
'/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-
dynload/collections.so'

However, this raises an exception on my Windows machine.

Python open() requires full path

I have identified the problem. I was running my code on Visual Studio Code debugger. The root directory I have opened was above the level of my file. When I opened the same directory, it worked.

How do I open a file in python with a relative path using with open()?

You can do it with:

import os
path = os.getenv('HOME') + '/scripts/config.yaml'

~ only works in shell, not in a Python string

Python - relative path with open(..) - function

open('/relative//path//to//file', 'r')

If its windows dont forget put // otherwise python will not interpret it properly

Open file from path relative to the system root python

If you are on linux you would need to add a / to the beginning of the path, for example to access /tmp/someFile.txt you would do open("/tmp/someFile.Txt"). This works because / references the root.

On windows (this has not been tested) i before you would do open("C:/someFile.txt").

The docs for the open function can be found at: https://docs.python.org/3/library/functions.html#open

python open all files ending with .txt in a relative folder

Don't worry about the Absolute path, below line gives you the Absolute path where your script runs.

import os

script_dir = os.path.dirname(__file__) # <-- absolute dir to the script is in

Now you can merge your relative path to the Absolute path

rel_path = 'relative_path_to_the_txt_dir'
os.path.join(script_dir, rel_path) # <-- absolute dir to the txt is in

If you print the above line you'll see the exact path your txt files located on.

Here is what you are looking for:-

import glob
import os

script_dir = os.path.dirname(__file__) # <-- absolute dir to the script is in
rel_path = 'relative_path_to_the_txt_dir'
txt_dir = os.path.join(script_dir, rel_path) # <-- absolute dir to the txt is in

for filename in glob.glob(os.path.join(txt_dir, '*.txt')): # filter txt files only
with open(os.path.join(os.getcwd(), filename), 'r') as file: # open in read-only mode
# do your stuff

Here are few links that you can understand what I did:-

  1. os.path.dirname(path)
  2. os.path.join(path, *paths)
  3. glob.glob(pathname, *, recursive=False)

References:-

  1. Open file in a relative location in Python
  2. How to open every file in a folder


Related Topics



Leave a reply



Submit