當前位置:生活全書館 >

綜合知識

> Python 判斷檔案/目錄是否存在 python 看是否存在資料夾

Python 判斷檔案/目錄是否存在 python 看是否存在資料夾

1、Python 操作檔案時,我們一般要先判斷指定的檔案或目錄是否存在,不然容易產生異常。

python 看是否存在資料夾 Python 判斷檔案/目錄是否存在

2、例如我們可以使用 os 模組的 os.path.exists() 方法來檢測檔案是否存在:

import os.path

os.path.isfile(fname)

3、如果你要確定他是檔案還是目錄,從 Python 3.4 開始可以使用 pathlib 模組提供的物件導向的方法 (Python 2.7 為 pathlib2 模組):

from pathlib import Path

my_file = Path(/path/to/file)

if my_file.is_file():

# 指定的檔案存在

檢測是否為一個目錄:

if my_file.is_dir():

# 指定的目錄存在

4、如果要檢測路徑是一個檔案或目錄可以使用 exists() 方法:

if my_file.exists():

# 指定的檔案或目錄存在

在 try 語句塊中你可以使用 resolve() 方法來判斷:

try:

my_abs_path = my_file.resolve()

except FileNotFoundError:

# 不存在

else:

# 存在

  • 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/zonghezhishi/nv3z66.html