从Windows批处理执行Python脚本时相对路径是否中断?
作者:互联网
如果我直接从它所在的目录中执行它,我的Python脚本就可以正常工作.但是如果我退出该目录并尝试从其他地方执行它(不更改任何代码或文件位置),所有相对路径都会中断得到一个FileNotFoundError.
该脚本位于./scripts/bin/my_script.py.有一个名为./scripts/bin/data/的目录.就像我说的那样,只要我从同一个目录执行它就完全可以工作……所以我很困惑.
成功执行(在./scripts/bin/中):python my_script.py
执行失败(在./scripts/中):python bin / my_script.py和python ./bin/my_script.py
失败消息:
Traceback (most recent call last):
File "./bin/my_script.py", line 87, in <module>
run()
File "./bin/my_script.py", line 61, in run
load_data()
File "C:\Users\XXXX\Desktop\scripts\bin\tables.py", line 12, in load_data
DATA = read_file("data/my_data.txt")
File "C:\Users\XXXX\Desktop\scripts\bin\fileutil.py", line 5, in read_file
with open(filename, "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'data/my_data.txt'
相关的Python代码:
def read_file(filename):
with open(filename, "r") as file:
lines = [line.strip() for line in file]
return [line for line in lines if len(line) == 0 or line[0] != "#"]
def load_data():
global DATA
DATA = read_file("data/my_data.txt")
解决方法:
是的,这是合乎逻辑的.这些文件是相对于您的工作目录的.您可以通过从其他目录运行脚本来更改它.
你可以做的是在运行时获取你正在运行的脚本的目录并从中构建.
import os
def read_file(filename):
#get the directory of the current running script. "__file__" is its full path
path, fl = os.path.split(os.path.realpath(__file__))
#use path to create the fully classified path to your data
full_path = os.path.join(path, filename)
with open(full_path, "r") as file:
#etc
标签:python,windows,batch-file,relative-path 来源: https://codeday.me/bug/20190725/1533292.html