Python如何在通过格式化程序时打开带有空格的文件路径
在将Python如何在通过格式化程序时打开带有空格的文件路径,python,Python,在将start命令与os.system一起使用时,如何运行需要包含空格的文件路径的命令 例如: # path_d[key] = C:\Users\John\Documents\Some File With Space.exe path = path_d[key] os.system("start {0}".format(path)) 当我试着运行它时,我最终得到一个错误,说: Windows cannot find 'C:\Users\John\Documents\Some.'. Make s
start
命令与os.system
一起使用时,如何运行需要包含空格的文件路径的命令
例如:
# path_d[key] = C:\Users\John\Documents\Some File With Space.exe
path = path_d[key]
os.system("start {0}".format(path))
当我试着运行它时,我最终得到一个错误,说:
Windows cannot find 'C:\Users\John\Documents\Some.'. Make sure you typed the name correctly, and then try again.
您需要正确转义
路径中的特殊字符,这可能很容易做到:
path = r"C:\Users\John\Documents\Some File With Space.exe"
要在Windows下执行,请执行以下操作:
import os
os.system(r"C:\Users\John\Documents\Some File With Space.exe")
编辑
根据OP的要求:
path_dict = {"path1": r"C:\Users\John\Documents\Some File With Space.exe"}
os.system('{}'.format(path_dict["path1"]))
您需要正确转义路径中的特殊字符,这可能很容易做到:
path = r"C:\Users\John\Documents\Some File With Space.exe"
要在Windows下执行,请执行以下操作:
import os
os.system(r"C:\Users\John\Documents\Some File With Space.exe")
编辑
根据OP的要求:
path_dict = {"path1": r"C:\Users\John\Documents\Some File With Space.exe"}
os.system('{}'.format(path_dict["path1"]))
我做以下几点
path = path_d[key]
os.system(r'start "{0}"'.format(path))
os.system(r'notepad "{0}"'.format(path))
因此,用双引号将路径括起来。这样,它将照顾路径中的空间。
如果没有要打开的默认应用程序,它可能会打开命令提示符。因此,如果是文本文件,请执行以下操作
path = path_d[key]
os.system(r'start "{0}"'.format(path))
os.system(r'notepad "{0}"'.format(path))
我做以下几点
path = path_d[key]
os.system(r'start "{0}"'.format(path))
os.system(r'notepad "{0}"'.format(path))
因此,用双引号将路径括起来。这样,它将照顾路径中的空间。
如果没有要打开的默认应用程序,它可能会打开命令提示符。因此,如果是文本文件,请执行以下操作
path = path_d[key]
os.system(r'start "{0}"'.format(path))
os.system(r'notepad "{0}"'.format(path))
如果文件路径存储为字典而不是硬编码,我该怎么做?@InAFlash我添加(编辑)了帖子,包括我执行它的方式,它在我的机器上的python2下运行良好。如果文件路径存储为字典而不是硬编码,我该怎么做?@InAFlash我添加(编辑)这篇文章包括我执行它的方式,它在我的机器上的python2下运行良好我尝试了这一点,它似乎导致打开一个命令提示符,标题作为路径名如果它是一个exe,你直接给exe路径,而不是把itI的开始信息放在os.system(r'start“random title”“{0}”format(path))
运行良好。如果您使用引号,MS-DOS“start”命令要求第一个参数有一个标题。@Sam,看起来它已经回答了。您链接的问题似乎不包括“start”调用的使用。我编辑了我的问题以反映这一点。我尝试了这一点,结果似乎是打开了一个命令提示符,标题作为路径名。如果它是一个exe,你直接给出exe的路径,而不是把itI的开始信息放在那里。我发现,os.system(r'start“random title”“{0}”“.format(path))
工作得很好。如果您使用引号,MS-DOS“start”命令要求第一个参数有一个标题。@Sam,看起来它已经回答了。您链接的问题似乎不包括“start”调用的使用。我编辑了我的问题以反映这一点。可能的重复可能的重复