You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从外部目录运行Python脚本时加载CSV文件失败的解决办法

问题:从外部目录运行Python脚本无法加载同目录CSV文件

当从main.py及CSV文件所在目录之外运行该脚本时,无法加载与main.py同目录的CSV文件。

在终端执行以下命令时:

$ python /home/bbartling/Desktop/Load-Shredder/Load-Shift/main.py

会出现CSV文件加载错误:

[Errno 2] No such file or directory: 'addresses_jci.csv'

但在Load-Shift目录内执行$ python main.py时,脚本可正常运行。

已在脚本顶部添加以下代码获取脚本目录:

script_dir = os.path.abspath( os.path.dirname( __file__ ) )
print("script directory: ",script_dir)

执行后输出正确的脚本路径:

script directory:  /home/bbartling/Desktop/Load-Shredder/Load-Shift

但问题仍未解决,求可行的解决思路。


补充说明:CSV加载函数代码

main.py中的CSV文件加载函数如下:

dir_path = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(dir_path, f'log_{dt_string}.log')
script_dir = os.path.abspath( os.path.dirname( __file__ ) )
print("script directory: ",script_dir)

def load_addresses(csv_file):
    try:
        print(f"Loading csv file: {csv_file}!")
        os.path.join(script_dir, f'{csv_file}.csv')
        with open(f'{csv_file}', newline='') as f:
            reader = csv.reader(f)
            data = list(reader)

        # flattens list of lists
        csv_file = sum(data, [])
        print(f"{csv_file} addresses loaded: ",csv_file)

    except Exception as error:
        print(f"CSV file load error: {error}")
        csv_file = [] # errors out

    return csv_file

问题分析与解决方案

你已经正确获取了脚本所在目录script_dir,但关键错误是调用os.path.join拼接路径后,没有将结果赋值给变量,依然直接使用原文件名打开文件。

修改后的load_addresses函数如下:

def load_addresses(csv_file):
    try:
        print(f"Loading csv file: {csv_file}!")
        # 拼接完整路径并赋值给变量
        full_csv_path = os.path.join(script_dir, f'{csv_file}.csv')
        with open(full_csv_path, newline='') as f:
            reader = csv.reader(f)
            data = list(reader)

        # flattens list of lists
        addresses = sum(data, [])
        print(f"{len(addresses)} addresses loaded: ", addresses)

    except Exception as error:
        print(f"CSV file load error: {error}")
        addresses = [] # errors out

    return addresses

修改要点:

  • 将os.path.join的结果赋值给full_csv_path变量,打开文件时使用这个完整路径
  • 避免用csv_file变量覆盖参数名(原代码中把加载后的列表赋值给了csv_file,易混淆),改用addresses作为变量名
  • 打印加载数量时用len(addresses)更合理,原代码直接打印列表内容会导致输出混乱

这样修改后,无论从哪个目录运行脚本,都会基于脚本所在目录去查找CSV文件,解决路径问题。


内容的提问来源于stack exchange,提问作者bbartling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:57:23