Python3如何檢查檔案或資料夾是否存在?

pythontab發表於2017-12-05

如何檢查一個檔案或者資料夾存在?有幾種方法,Python2和Python3版本也有不同,這是在檔案操作中常用到的方法,只有檔案存在我們才可以繼續對檔案進行處理,下面總結了常用的檢查檔案是否存在的方法。

本程式碼在Python3.4+下透過, 其他版本略有差異

使用os庫

不需要開啟檔案,直接使用os庫方法檢查

import os.path
filename='/pythontab.com/file.txt'
os.path.isfile(filename)

檢查檔案是否存在,成功返回Ture, 失敗返回False

注意:僅能檢測檔案, 而非資料夾

資料夾檢查

os.path.exists即可以檢查檔案也可以檢查資料夾

import os
a_path='/pythontab.com/'
if os.path.exists(a_path):
    #do something

檔案許可權檢查

上面僅檢查了檔案是否存在,並沒有檢查是否可讀或者可寫, 可以使用os.access方法

import os
filename='/pythontab.com/file.txt'
if os.path.isfile(filename) and os.access(filename, os.R_OK):
    #do something

既檢查了檔案是否存在,又檢查了檔案是否可讀

使用pathlib庫

從Python3.4開始,python已經把pathlib加入了標準庫,不需要自己安裝,但Python2版本需要使用pip安裝pathlib2

檔案是否存在

from pathlib import Path
my_file = Path("/pythontab.com/file.txt")
if my_file.is_file():
    # file exists

資料夾是否存在

if my_file.is_dir():
    # directory exists

檔案或資料夾是否存在

if my_file.exists():
    # path exists

上面就是檢查檔案或資料夾是否存在的方法,如有問題,歡迎留言


相關文章