基本上,我试图在python中使用os.system运行命令提示符命令来打开一个图像。问题是,我将会把代码和图像传输给一个文件夹内的其他人,所以我希望代码能够工作,不管文件夹放在什么目录下。我写了一些代码,可以找到图片的当前目录,并把它放在一个变量中,但我不知道如何运行命令,如果它的一部分是一个变量,而不是一个长字符串。有什么技巧吗,或者有什么更简单的方法吗?
import os
#Gets/formats directory
def getDirect():
x = list(os.getcwd())
y = ""
for c in x:
if c == "\\":
c = "\\\\"
for c in x:
y = y + c
y = y + "\\imageNameHere.png"
return y
#Prints a valid directory name
print(getDirect())
#Cmd says "The directory name is invalid"
os.system('cmd /k "cd "' + getDirect())
使用相对路径[1]
这样一来,只要他把整个文件夹移动,他的文件放在哪里都无所谓。
例如
Folder --> script --> script.py
文件夹 --> image --> image.jpeg。
那么相对路径就是...imageimage.jpeg。