TLDR:我想在双击脚本文件时将其工作目录更改为脚本文件的位置(而不是system32)。
我有一个很烦人的问题,我解决不了。我正在构建一个python脚本,它将4个文本文件作为输入,并使用这些文本文件创建一些图形和excel工作表。我将把我的脚本传递给一个朋友,他将把脚本复制到不同的文件夹中,并通过双击脚本在这些文件夹中执行脚本。我面临的问题是,当我用cmd执行代码时,一切正常。但是如果我双击它,我的代码所在的目录会自动改变,我的程序也找不到所需的4个文本文件。我在下面附上我的代码的必要部分,并附上一些屏幕截图。
ss1
ss2
def fileOpenCheckLoad(fname):
pl=list()
try:
fh=open(fname)
except:
print("ERROR:"+ fname +" is missing. Execution will terminate.")
x=input("Press enter to quit.")
quit()
test1=fh.readline()
test2=fh.readline()
if test1[6]!=fname[5] and test2!='t x y\n' :
print("ERROR: Check the contents of:"+ fname)
x=input("Press enter to quit.")
quit()
count=0
for lines in fh:
count=count+1
if count>2 :
nums=lines.split()
pl.append((float(nums[2]), float(nums[2])))
tbr=(pl,count-2)
return tbr
# main starts here.
cwd = os.getcwd()
print(cwd)
# In this part we open and load files into the memory. If there is an error we terminate.
(pl1, count1)=fileOpenCheckLoad('point1.txt')
(pl2, count2)=fileOpenCheckLoad('point2.txt')
(pl3, count3)=fileOpenCheckLoad('point3.txt')
(pl4, count4)=fileOpenCheckLoad('point4.txt')
在调用
os.getcwd()
之前,插入以下行:解释
__file__
是Python中的一个特殊变量;如here所述,“__file__
是从中加载模块的文件的路径名”os.path.abspath
返回输入文件或目录的绝对路径(我之所以包括这个,是因为根据加载Python文件的方式,有时__file__
将存储为相对路径,而绝对路径往往更安全)os.path.dirname
返回包含输入文件的目录的名称(因为chdir
如果我们给它一个文件名,它将返回一个错误,所以我们需要给它一个包含该文件的目录的名称)os.chdir
更改工作目录相关问题 更多 >
编程相关推荐