python如何判斷一個目錄下是否存在某個文件?


python如何判斷一個目錄下是否存在某個文件?

1.使用os模塊

  • 用os模塊中baios.path.exists()方法檢測是否存在test_file.txt文件
    import os
    os.path.exists(test_file.txt)
    #True
    os.path.exists(no_exist_file.txt)
    #False
    

      

2.使用Try命令

  • 使用open()方法,如果要打開的文件不存在,就回跑出異常,用try()方法捕獲異常。
    try:
      f =open(test_file.txt)
      f.close()
    except IOError:
      print "file is not accessible"
    

      

3. 使用pathlib

  • 檢查路徑是否存在
    path = pathlib.Path("path/file")
    path.exist()
    

      

  • 檢查路徑是否是文件
    path = pathlib.Path("path/file")
    path.is_file()
    

      

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM