在Python中管理文件路径的最佳实践
在我的python项目中,我经常使用/data
-Directory我存储资源。
我现在想从不同的脚本访问这些资源,我看到的一个选项是使用文件的相对路径:
open('./../data/myFile.csv')
这里的问题是,它不使用相对于Pyhton脚本目录的路径,而是用于路径相对的路径到我运行Python的目录。我已经有很多问题了。
对我来说更好的是使用
scriptDir = os.path.dirname(os.path.realpath(__file__))
join(scriptDir, './../data/myFile.csv')
更好的解决方案?到目前为止,我从未见过我的解决方案,所以我想知道我是否错过了一些人或是否有更好的侵犯。
谢谢 :)
in my python-Projects I often use a /data
-directory where I store resources.
I now want to access these resources from different scripts, one option I see is to use the relative path of the file:
open('./../data/myFile.csv')
The problem here is that it doesn't use the path relative to the directory of the pyhton script but to the path relative to the directory in which i run python. I already had a lot of problems with that.
What works better for me is using
scriptDir = os.path.dirname(os.path.realpath(__file__))
join(scriptDir, './../data/myFile.csv')
Is there any better solution to my problem? I so far never saw my solution so I'm wondering if I am missing somehing or if there is any better aproach.
Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种明智的方法是导出
环境variabile
或在config.ini
或settings.py
中设置常数您想要并将其连接到data/myfile.csv
喜欢的路径:
settings.py
main
例如
,
。 main.py:
A smart way to do that is to export an
environment variabile
or to set a constant in aconfig.ini
orsettings.py
with the base path you want and concatenate it todata/myFile.csv
Like so:
settings.py
main.py
You may also launch your python code through a bash script where you do this:
launch.sh
And in the main.py: