Skip to content Skip to sidebar Skip to footer

Weird Python File Path Behavior

I have this folder structure, within edi_standards.py I want to open csv/transaction_groups.csv But the code only works when I access it like this os.path.join('standards', 'csv',

Solution 1:

when you're running a python file, the python interpreter does not change the current directory to the directory of the file you're running.

In your case, you're probably running (from ~/edi_parser):

standards/edi_standards.py

For this you have to hack something using __file__, taking the dirname and building the relative path of your resource file:

os.path.join(os.path.dirname(__file__),"csv","transaction_groups.csv")

Anyway, it's good practice not to rely on the current directory to open resource files. This method works whatever the current directory is.

Solution 2:

I do agree with Answer of Jean-Francois above, I would like to mention that os.path.join does not consider the absolute path of your current working directory as the first argument For example consider below code

>>> os.path.join('Functions','hello')
'Functions/hello'

See another example

>>> os.path.join('Functions','hello','/home/naseer/Python','hai') '/home/naseer/Python/hai'

Official Documentation states that whenever we have given a absolute path as a argument to the os.path.join then all previous path arguments are discarded and joining continues from the absolute path argument.

The point I would like to highlight is we shouldn't expect that the function os.path.join will work with relative path. So You have to submit absolute path to be able to properly locate your file.

Post a Comment for "Weird Python File Path Behavior"