搜尋
首頁後端開發Python教學Python中使用三種方法判斷檔案或資料夾是否存在的實例分享

本文要為大家介紹三種判斷檔案或資料夾是否存在的方法,分別使用os模組、Try語句、pathlib模組。有興趣的朋友一起看看吧

常在讀寫檔案之前,需要判斷檔案或目錄是否存在,不然某些處理方法可能會使程式出錯。所以最好在做任何操作之前,先判斷文件是否存在。

這裡將介紹三種判斷檔案或資料夾是否存在的方法,分別使用os模組、Try語句、pathlib模組。

1.使用os模組

os模組中的os.path.exists()方法來檢驗檔案是否存在。

  • 判斷檔案是否存在


#
import os
os.path.exists(test_file.txt)
#True
os.path.exists(no_exist_file.txt)
#False
  • 判斷資料夾是否存在


import os
os.path.exists(test_dir)
#True
os.path.exists(no_exist_dir)
#False

可以看出用os.path.exists()方法,判斷檔案和資料夾是一樣。

其實這種方法還是有個問題,假設你想檢查檔案「test_data」是否存在,但是目前路徑下有個叫「test_data」的資料夾,這樣就可能會出現誤判。為了避免這樣的情況,可以這樣:

  • 只檢查檔案


#
import os
os.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 os
if 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中使用三種方法判斷檔案或資料夾是否存在的實例分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具