Python中如何判斷檔案是否存在?

來源:互聯網
上載者:User

標籤:

通常在讀寫檔案之前,需要判斷檔案或目錄是否存在,不然某些處理方法可能會使程式出錯。所以最好在做任何操作之前,先判斷檔案是否存在。 本文為大家介紹三種判斷檔案或檔案夾是否存在的方法,分別使用 os模組 、 Try語句 、 pathlib模組 ,一起來看看吧,希望對大家學習python有所協助。 1.使用os模組 os模組中的 os.path.exists() 方法用於檢驗檔案是否存在。 · 判斷檔案是否存在 import osos.path.exists(test_file.txt)#True os.path.exists(no_exist_file.txt)#False · 判斷檔案夾是否存在 import osos.path.exists(test_dir)#True os.path.exists(no_exist_dir)#False 可以看出用 os.path.exists() 方法,判斷檔案和檔案夾是一樣。 其實這種方法還是有個問題,假設你想檢查檔案“test_data”是否存在,但是當前路徑下有個叫“test_data”的檔案夾,這樣就可能出現誤判。為了避免這樣的情況,可以這樣: · 只檢查檔案 import osos.path.isfile("test-data") 通過這個方法,如果檔案”test-data”不存在將返回False,反之返回True。 即是檔案存在,你可能還需要判斷檔案是否可進行讀寫操作。 判斷檔案是否可做讀寫操作 使用 os.access() 方法判斷檔案是否可進行讀寫操作。 文法: os.access(, ) path為檔案路徑,mode為操作模式,有這麼幾種: ·os.F_OK: 檢查檔案是否存在; ·os.R_OK: 檢查檔案是否可讀; ·os.W_OK: 檢查檔案是否可以寫入; ·os.X_OK: 檢查檔案是否可以執行 該方法通過判斷檔案路徑是否存在和各種訪問模式的許可權返回True或者False。 import osif os.access("/file/path/foo.txt", os.F_OK): print "Given file path is exist." if os.access("/file/path/foo.txt", os.R_OK): print "File is accessible to read" if os.access("/file/path/foo.txt", os.W_OK): print "File is accessible to write" if os.access("/file/path/foo.txt", os.X_OK): print "File is accessible to execute" 2.使用Try語句 可以在程式中直接使用 open() 方法來檢查檔案是否存在和可讀寫。 文法: open() 如果你open的檔案不存在,程式會拋出錯誤,使用try語句來捕獲這個錯誤。 程式無法訪問檔案,可能有很多原因: ·如果你open的檔案不存在,將拋出一個 FileNotFoundError 的異常; ·檔案存在,但是沒有許可權訪問,會拋出一個 PersmissionError 的異常。 所以可以使用下面的代碼來判斷檔案是否存在: try: f =open() f.close()except FileNotFoundError: print "File is not found."except PersmissionError: print "You don’t have permission to access this file." 其實沒有必要去這麼細緻的處理每個異常,上面的這兩個異常都是 IOError 的子類。所以可以將程式簡化一下: try: f =open() f.close() except IOError: print "File is not accessible." 使用try語句進行判斷,處理所有異常非常簡單和優雅的。而且相比其他不需要引入其他外部模組。 3. 使用pathlib模組 pathlib模組在Python3版本中是內建模組,但是在Python2中是需要單獨安裝三方模組。 使用pathlib需要先使用檔案路徑來建立path對象。此路徑可以是檔案名稱或目錄路徑。 · 檢查路徑是否存在 path = pathlib.Path("path/file") path.exist() · 檢查路徑是否是檔案 path = pathlib.Path("path/file") path.is_file()來源:部落格園

Python中如何判斷檔案是否存在?

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.