[Python] 檔案是否存在

  • 124
  • 0
  • 2019-09-02

#判斷檔案是否存在

# Python 3.7

 

 

import os

listPath = ["apple.txt", "egg.txt", "banana.txt"]
for file in listPath:
    _strPath = "C:\\"+file
    isExt = os.path.exists(_strPath) #can instead use os.path.isfile() 
    if(isExt == True):
        print(file + " --> Exist")
    else:
        print(file + " --> No exist")
apple.txt --> Exist
egg.txt --> No exist
banana.txt --> No exist

 

ref:https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions?page=1&tab=votes#tab-top