我在c:\codes\Python\CGLB\util\subprocessUtils.py 中写了这样一段代码:
testClass_place_path = f"../txt_repo/csv_plus/evo_testClass_place.json"
def main():
with open(testClass_place_path, "r") as f:
print(f.read())
其中evo_testClass_place.json这个文件确实存在于C:\codes\Python\CGLB\txt_repo\csv_plus目录下,但是却得到报错:
FileNotFoundError: [Errno 2] No such file or directory: '../txt_repo/csv_plus/evo_testClass_place.json'?
在问过Grimoire后,它告诉我通常是由于当前工作目录(current working directory)与预期的不一致导致。
动态生成文件的绝对路径,代码如下
import os
def get_absolute_path(relative_path):
# 获取当前脚本的绝对路径
dir_of_this_script = os.path.dirname(os.path.abspath(__file__))
# 构建到目标文件的绝对路径
return os.path.join(dir_of_this_script, relative_path)
testClass_place_path = get_absolute_path("../txt_repo/csv_plus/evo_testClass_place.json")
def main():
with open(testClass_place_path, "r") as f:
print(f.read())
问题解决*★,°*:.☆( ̄▽ ̄)/$:*.°★* 。