繁体   English   中英

Python检查文件是否存在(返回false,应返回true)

[英]Python checking if file exists (returns false, should return true)

我有以下代码行:

tfPath = '\"' + os.environ["ProgramFiles(x86)"] + '\Microsoft Visual Studio 12.0\Common7\IDE\TF.exe\"'
if not os.path.exists(tfPath):
    tfPath = 'TF.exe'
cmd_str = '\"' + tfPath + ' checkout ' + '\"Files_to_checkout\"\"'

我按照"C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\IDE\\TF.exe"所述的文件进行了测试。 但是我的代码总是跳到了真正的分支中,所以它从来没有承认文件实际上在那里。 我在那里做错了什么?

请注意,出于测试目的,我对原始tfPath做了os.system(cmd_str) ,它工作正常,因此该文件存在,可以访问,但是path.os.exists每次都返回false。

尝试在第一次分配给tfPath的过程中删除多余的引号。 您需要在系统调用中使用它们,以防止带有嵌入式空间的路径被外壳分割。 但是对os.path.exists的调用不需要引用它; 实际上,我认为它将'“'视为文件名的一部分,该文件名不存在。

tfPath = os.environ["ProgramFiles(x86)"] + '\Microsoft Visual Studio 12.0\Common7\IDE\TF.exe'
if not os.path.exists(tfPath):
    tfPath = 'TF.exe'
cmd_str = '\"' + tfPath + ' checkout ' + '\"Files_to_checkout\"\"'

不知道出了什么问题。 尝试:

tfPath = os.path.join(os.environ["ProgramFiles(x86)"], 
    r'Microsoft Visual Studio 12.0\Common7\IDE\TF.exe')
if os.path.exists(tfPath):
    print('tfPath={} exists'.format(tfPath))
else:
    print('tfPath={} does not exist'.format(tfPath))

(修复了\\\\\\替换的复制/粘贴错误,因此我添加了原始字符串r''指示符,因此上面的代码段应该可以直接使用。此外,还结合了GreenMat的建议,我使用+替换了字符串连接,并调用了os.path.join

编辑答案:测试显示您提供的代码产生以下路径名:

“ C:\\ Program Files(x86)\\ Microsoft Visual Studio 12.0 \\ Common7 \\ IDE \\ TF.exe”

换句话说,您正在构建的路径名包含双引号。 但是,它们不在实际的路径规范中。 这就是为什么您的代码无法找到所需文件的原因。

使用os.path.join来构建路径名是更pythonic的和更少的错误倾向

它应该看起来像这样:

tfPath = os.path.join(os.environ["ProgramFiles(x86)"], 'Microsoft Visual Studio 12.0', 'Common7', 'IDE', 'TF.exe')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM