[英]Python add path of data directory
I want to add a path to my data directory in python, so that I can read/write files from that directory without including the path to it all the time.我想在 python 中添加到我的数据目录的路径,这样我就可以从该目录读取/写入文件,而无需始终包含它的路径。
For example I have my working directory at /user/working
where I am currently working in the file /user/working/foo.py
.例如,我的工作目录位于/user/working
中,我当前在文件/user/working/foo.py
中工作。 I also have all of my data in the directory /user/data
where I want to excess the file /user/data/important_data.csv
.我的所有数据也都在目录/user/data
中,我想在其中超出文件/user/data/important_data.csv
。
In foo.py
, I could now just read the csv with pandas using在foo.py
中,我现在可以使用 pandas 读取 csv
import pandas as pd
df = pd.read_csv('../data/important_data.csv')
which totally works.这完全有效。 I just want to know if there is a way to include /user/data
as a main path for the file so I can just read the file with我只想知道是否有办法将/user/data
作为文件的主路径,这样我就可以读取文件了
import pandas as pd
df = pd.read_csv('important_data.csv')
The only idea I had was adding the path via sys.path.append('/user/data')
, which didnt work (I guess it only works for importing modules).我唯一的想法是通过sys.path.append('/user/data')
添加路径,这没有用(我猜它只适用于导入模块)。
Is anyone able to provide any ideas if this is possible?如果可能的话,有人能提供任何想法吗?
PS: My real problem is of course more complex, but this minimal example should be enough to handle my problem. PS:我真正的问题当然更复杂,但这个最小的例子应该足以解决我的问题。
If you are keeping everything in /user/data
, why not use f-strings to make this easy?如果您将所有内容都保存在/user/data
中,为什么不使用 f-strings 来简化此操作呢? You could assign the directory to a variable in a config and then use it in the string like so:您可以将目录分配给配置中的变量,然后像这样在字符串中使用它:
In a config somewhere:在某处的配置中:
data_path = "/user/data"
Reading later...以后读书...
df = pd.read_csv(f"{data_path}/important_data.csv")
It looks like you can use os.chdir
for this purpose.看起来您可以为此目的使用os.chdir
。
import os
os.chdir('/user/data')
See https://note.nkmk.me/en/python-os-getcwd-chdir/ for more details.有关详细信息,请参阅https://note.nkmk.me/en/python-os-getcwd-chdir/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.