奇怪的python文件路径行为 [英] Weird python file path behavior

查看:77
本文介绍了奇怪的python文件路径行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有此文件夹结构,在edi_standards.py之内,我想打开csv/transaction_groups.csv

I have this folder structure, within edi_standards.py I want to open csv/transaction_groups.csv

但是该代码仅在像这样os.path.join('standards', 'csv', 'transaction_groups.csv')

But the code only works when I access it like this os.path.join('standards', 'csv', 'transaction_groups.csv')

我认为应该是os.path.join('csv', 'transaction_groups.csv'),因为edi_standards.pycsv/都位于同一文件夹standards/

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/

这是打印__file__的输出,以防您怀疑我在说什么:

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

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

推荐答案

当您运行python文件时,python解释器不会将当前目录更改为您的文件目录重新运行.

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.

以您为例,您可能正在运行(来自~/edi_parser):

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

standards/edi_standards.py

为此,您必须使用__file__破解某些东西,并使用目录名并构建资源文件的相对路径:

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.

这篇关于奇怪的python文件路径行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆