简体   繁体   中英

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', 'transaction_groups.csv')

What I think it should be is os.path.join('csv', 'transaction_groups.csv') since both edi_standards.py and csv/ are on the same level in the same folder standards/

This is the output of printing __file__ in case you doubt what I say:

>>> print(__file__)
~/edi_parser/standards/edi_standards.py

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM