首页 > 解决方案 > 为什么从 IDLE 调用时 Numpy.loadtxt 工作,从 shell 调用时给出 IOError?

问题描述

我尝试执行以下操作:

1 VBA脚本调用shell使用

RetVal = Shell(fullpythonexepath & fullscriptpath)

2 Shell 获取以下命令

fullpythonexepath & fullscriptpath

3 Python 脚本

import numpy as np

thefilepath = "input.txt"    # is in the same folder as the script
theoutputpath = "output.txt" # is in the same folder as the script

ssc=np.loadtxt(thefilepath, delimiter='\t', skiprows=0, usecols=range(2)) #error line

#some other code to fit input data

np.savetxt(theoutputpath, sscnew, header=top, fmt='%1.2f\t%1.2f') 

当我运行它时,输出文件不会被打印出来,这意味着脚本不能正常运行。

现在来个有趣的事情:当我从 IDLE 运行 python 脚本时,它运行良好。当我使用以下命令从 shell 运行它时:

fullpythonexepath & fullscriptpath

它说 :

在此处输入图像描述

解决方案是:

import os 
os.chdir(r"fullpath")

在我的脚本中,这会将当前工作目录更改为我的路径,然后找到 input.txt。

标签: pythonexcelvbashellnumpy

解决方案


当您从 shell 启动脚本时,脚本的工作目录将是调用它的目录。大多数 IDLE 都定义了自己的工作目录。要检查我建议这样做:

os.getcwd()

在这两种情况下,看看在这两种情况下都使用了什么目录


推荐阅读