Python 判斷檔案 目錄是否存在

2021-09-30 01:48:21 字數 783 閱讀 5518

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

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

import os.path

os.path.isfile(fname)

如果你要確定他是檔案還是目錄,從 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(

): # 指定的目錄存在

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

if my_file.exists(

): # 指定的檔案或目錄存在

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

try:

my_abs_path = my_file.resolve(

)except filenotfounderror:

# 不存在

else:

# 存在

Linux shell判斷檔案或目錄是否存在

這裡的 x 引數判斷 mypath是否存在並且是否具有可執行許可權 if x mypath then mkdir mypath fi 這裡的 d 引數判斷 mypath是否存在 if d mypath then mkdir mypath fi 這裡的 f引數判斷 myfile是否存在 if f my...

php判斷是否是檔案 php 判斷檔案是否存在

sha1 file 計算文字檔案sha 1雜湊 sha1 file file 語法 sha1 file file,raw 引數 file 必需。規定要計算的檔案。raw 可選。布林值,規定十六進製制或二進位制輸出格式 true 原始 16 字元二進位制格式 false 預設。32 字元十六進製制數 ...

shell小技巧實戰 判斷檔案或目錄是否存在

在編寫shell指令碼時,通常最開始的工作是對環境的檢查,比如檢查某一檔案或目錄是否存在,並執行相應的操作等。下面的shell指令碼實現的功能是,先檢查某一目錄是否存在,不存在的話就建立此目錄,存在的話就cd到這個目錄下。bin bash 指定用到的shell直譯器 export mypath tm...