我想使用变量作为文件路径。
with open(list, 'r') as f:
line= f.readlines()
for path in line:
print ("file_path")
print (path)
subprocess.Popen(path, shell=True)
但是控制台说...
file_path
'C://User//Public//Documents//Test test//test.txt'
'C://User//Public//Documents//Test' is not recognized as an internal or external command, operable program or batch file.
你能帮我吗?
发布于 2021-07-14 09:48:41
你的代码有几处地方出了问题。
就被空格切割的路径而言,这是因为路径中有一个嵌入的空格字符。这是因为如果Popen()
的第一个参数是字符串,则该字符串将被解释为要执行的程序的名称或路径-请参阅documentation。但是,您的路径中有一个空格字符,因此您需要将整个路径括在双引号字符中。
其次,文件中的每一行都将有一个尾随的换行符,需要将其删除。第三,文件中的路径是错误的-它们似乎包含在单引号字符中,并且其中的正斜杠字符是双引号。
最后,您不应该为变量指定与Python内置相同的名称,如list
。
哇,这让我想起了我曾经听过的一句话:“犯错是人之常情,但真正把事情搞砸需要一台电脑”--因为在你的问题中,错误的数量几乎和代码行一样多。
无论如何,假设文件的格式为每行一个路径,如下所示:
C:/User/Public/Documents/Test test/test.txt
C:/User/Public/Documents/Test test/another_test.txt
... etc
以下代码应该可以执行您想要的操作:
pathfile = 'paths.txt'
with open(pathfile, 'r') as file:
for line in file:
path = f'"{line.rstrip()}"' # Strip training newline and enclose in quotes.
print("file_path")
print(path)
subprocess.Popen(path, shell=True)
https://stackoverflow.com/questions/68370682
复制相似问题