提问人:Bire 提问时间:10/18/2023 更新时间:10/19/2023 访问量:57
FileNotFoundError 当我使用来自其他目录的 read_csv 调用文件 [duplicate] 时
FileNotFoundError when I call a file with read_csv from an other directory [duplicate]
问:
在我的代码中,我有一个名为 location.py 的文件,我在其中读取一个用于函数分配的文件:
import pandas as pd
filename = '../../Dataset/Import.csv'
df = pd.read_csv(filename, sep='\t', encoding='utf-16')
def assign(df = df):
现在,我想在另一个文件中使用函数 assign,该文件位于其他目录中,但我遇到了错误:
FileNotFoundError: [Errno 2] No such file or directory:
如果我回到 location.py 并更改文件名的相对路径,一切正常。但是我希望python读取写入它的文件夹的相对路径,而不是从我调用函数的位置读取。 这是目录结构
- 目录 A -- location.py
- 数据 --进口
- 目录 b -- 另一个目录 -- file_from_where_I_call_location.py
我仍然想使用相对路径,但是我该如何解决这个问题?我不能在每次需要时都更改硬编码的文件路径
答:
0赞
Thomas
10/19/2023
#1
这是因为相对路径是相对于当前工作目录解析的。您可以通过以下方式检索脚本的目录:"../../Dataset/Import.csv"
pathlib.Path
__file__
pathlib.Path(__file__).parent
import pandas as pd
from pathlib import Path
script_path = Path(__file__).parent
file_path = script_path / "../../Dataset/Import.csv"
# or if you want an absolute path (however, not needed for pd.read_csv)
# file_path = (script_path / "../../Dataset/Import.csv").resolve()
df = pd.read_csv(file_path, sep="\t", encoding="utf-16")
def assign(df=df): # <- side note: df=df may not be a good idea (mutual object)
pass
评论