Windows终端用完整路径运行Python脚本时pd.to_datetime报错
问题分析与解决:PowerShell用完整路径执行Python脚本触发Pandas KeyError
问题现象
报错信息
line 3802, in get_loc return self._engine.get_loc(casted_key) File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\hashtable_class_helper.pxi", line 5745, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas\_libs\hashtable_class_helper.pxi", line 5753, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'last trade time'
运行方式差异
- 集成终端执行
python test_blah.py:运行正常 - Windows PowerShell导航至脚本目录后执行
python test_blah.py:运行正常 - Windows PowerShell用完整路径执行
python "G:\My Drive\darren\python\test_blah.py":触发上述KeyError
最小复现代码
import pandas as pd print('pandas version:' , pd.__version__) def some_function(): df = pd.read_csv('basic_GBP_stats.csv') print(df) print('got here 01') try: df['time'] = pd.to_datetime(df['last trade time']) print('got here 02') except Exception as e: print('exception found:', e) some_function()
说明:示例CSV文件包含last trade time列,使用pandas 1.5.3版本。
原因分析
核心问题是工作目录不一致:
- 前两种运行方式中,Python的工作目录就是脚本所在目录,
pd.read_csv('basic_GBP_stats.csv')能正确读取同目录下的目标CSV文件。 - 第三种运行方式中,PowerShell的工作目录是当前打开的路径(并非脚本所在目录),此时
pd.read_csv读取的是PowerShell当前目录下的文件——如果该目录下没有basic_GBP_stats.csv,pandas会创建空DataFrame(或读取了其他同名文件),自然找不到last trade time列,触发KeyError。
解决办法
方案1:读取CSV时使用脚本所在目录的绝对路径
修改代码,让脚本自动获取自身所在目录,拼接CSV文件路径,确保无论从哪里执行都能找到正确文件:
import pandas as pd import os # 获取脚本所在目录的绝对路径 script_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接CSV文件的完整路径 csv_full_path = os.path.join(script_dir, 'basic_GBP_stats.csv') print('pandas version:' , pd.__version__) def some_function(): df = pd.read_csv(csv_full_path) print(df) print('got here 01') try: df['time'] = pd.to_datetime(df['last trade time']) print('got here 02') except Exception as e: print('exception found:', e) some_function()
方案2:执行脚本前先切换到脚本所在目录
在PowerShell中先切换到脚本目录,再执行脚本:
cd "G:\My Drive\darren\python" && python test_blah.py
方案3:用PowerShell命令指定工作目录执行
使用Start-Process命令指定脚本所在目录为工作目录:
Start-Process -FilePath python -ArgumentList "G:\My Drive\darren\python\test_blah.py" -WorkingDirectory "G:\My Drive\darren\python" -NoNewWindow
内容的提问来源于stack exchange,提问作者darren
相关产品推荐
相关产品推荐

