简体   繁体   中英

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

I have following line of code:

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\"\"'

I tested with the file as described being there, in "C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\IDE\\TF.exe" . But my code ALWAYS jumped into the true branch, so it never acknowledged that the file was actually there. What did I do wrong there?

Note, for testing purposes, I did a os.system(cmd_str) with the original tfPath , which worked fine, so the file exists, it could be accessed, but the path.os.exists returns false every time.

Try removing the extra quotes in your first assignment to tfPath. You need them in the system call to keep the path with an embedded space from being split by the shell. But the call to os.path.exists does not need it quoted; in fact, I think it will treat the '"' as being part of the filename, which does not exist.

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\"\"'

Not sure what is going wrong. Try:

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))

(Fixed copy/paste mistake where \\\\ were being replaced by \\ , so I added a raw string, r'' indicator, so the snippet above should work directly. Also incorporating suggestion from GreenMat, I replaced string concatenation using + with call to os.path.join )

Edited answer: Testing shows that the code you presented produces the following pathname:

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

In other words, the pathname you are building contains the double quotes. However, they are not in the actual path specification. This is why your code fails to find the file you want.

It is more pythonic and less error prone to build the pathname using os.path.join

It ought to look something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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