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

问题描述 投票:0回答:1

在我的 python 项目中,我经常使用

/data
目录来存储资源。

我现在想从不同的脚本访问这些资源,我看到的一种选择是使用文件的相对路径:

open('./../data/myFile.csv')

这里的问题是它不使用相对于 pyhton 脚本目录的路径,而是使用相对于我运行 python 的目录的路径。我已经遇到很多问题了。

对我来说更有效的是使用

scriptDir = os.path.dirname(os.path.realpath(__file__))
join(scriptDir, './../data/myFile.csv')

我的问题有更好的解决办法吗?到目前为止,我从未见过我的解决方案,所以我想知道我是否遗漏了某些内容或者是否有更好的方法。

谢谢:)

python file path
1个回答
2
投票

一个聪明的方法是导出

environment variabile
或在
config.ini
settings.py
中设置一个常量与您想要的基本路径,并将其连接到
data/myFile.csv

像这样:

设置.py

BASE_PATH = "/your/directory"

main.py

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

您还可以通过 bash 脚本启动您的 Python 代码:

export BASE_PATH=$(pwd) # you set the BASE_PATH automatically, using pwd command. It's far more portable, 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"]
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.