簡體   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