在Python中管理文件路径的最佳实践

发布于 2025-02-13 06:18:23 字数 441 浏览 3 评论 0原文

在我的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久光 2025-02-20 06:18:23

一种明智的方法是导出环境variabile或在config.inisettings.py中设置常数您想要并将其连接到data/myfile.csv喜欢的路径

settings.py

BASE_PATH = "/your/directory"

main

from settings import BASE_PATH
os.path.dirname(f"{BASE_PATH}/myFile.csv")

例如

export BASE_PATH=$(pwd) # by setting the BASE_PATH automatically, you won't have to change it every time
virtualenv venv
source venv/bin/activate
pip3 install -r requirements.txt
python3 main.py
deactivate

。 main.py:

import os
base_path = os.environ["BASE_PATH"]

A smart way to do that is to export an environment variabile or to set a constant in a config.ini or settings.py with the base path you want and concatenate it to data/myFile.csv

Like so:

settings.py

BASE_PATH = "/your/directory"

main.py

from settings import BASE_PATH
os.path.dirname(f"{BASE_PATH}/myFile.csv")

You may also launch your python code through a bash script where you do this:

launch.sh

export BASE_PATH=$(pwd) # by setting the BASE_PATH automatically, you won't have to change it every time
virtualenv venv
source venv/bin/activate
pip3 install -r requirements.txt
python3 main.py
deactivate

And in the main.py:

import os
base_path = os.environ["BASE_PATH"]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文