1. 程式人生 > >利用python檢查檔案或資料夾是否存在

利用python檢查檔案或資料夾是否存在

在深度學習中,我們經常會用到判斷一個檔案或者資料夾是否存在,如果不存在的話那麼我們需要建立一個。那麼判斷檔案和資料夾是否存在常用的有哪些函數了?這裡逐一給您娓娓道來。

0. 準備

首先我們建立如下所示的層級結構,我們在/home/os_test之下,建立起一個資料夾dir還有兩個txt檔案file.txt,link.txt
在這裡插入圖片描述

因為我們這裡是使用python程式碼,需要用到os這個包,所以我們匯入import os

1. 檢查某個檔案是否存在: os.path.isfile

1.1 函式定義:

os.path.isfile(path)

  • Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

注意:這裡的path是檔案所處的路徑,注意字尾名也是需要加上的。

1.2 具體使用

import os  
os.path.isfile('./file.txt')    # True  
os.path.isfile('./link.txt')    # True  
os.path.isfile(
'./file') # False, 需要指定字尾名,否則不能識別 os.path.isfile('./link') # False os.path.isfile('./dir') # False

在這裡插入圖片描述

2. 檢查某個資料夾是否存在: os.path.isdir

2.1 函式定義:

os.path.isdir(path)

  • Return True if path is an existing directory. This follows symbolic links, so both islink() and isdir() can be true for the same path.

注意:這裡的path是檔案所處的路徑。

2.2 具體使用

import os  
os.path.isdir('./file.txt')    # False  
os.path.isdir('./link.txt')    # False  
os.path.isdir('./file')       # False
os.path.isdir('./link')       # False
os.path.isdir('./dir')    # True,只有這個才是真正的資料夾,所以返回True  

在這裡插入圖片描述

3. 檢查某個檔案或者資料夾是否存在: os.path.exists

3.1 函式定義:

os.path.exists(path)

  • Return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.

注意:檔案或者資料夾都返回True。

3.2 具體使用

import os  
os.path.exists('./file.txt')    # True  檔案返回true
os.path.exists('./link.txt')    # True  
os.path.exists('./file')       # False
os.path.exists('./link')       # False
os.path.exists('./dir')    # True 資料夾也返回True  

在這裡插入圖片描述

4. 擴充套件: os.path.exists和os.path.isfile的不同

這個問題也出現在stackoverflow上,Difference between os.path.exists and os.path.isfile in python. 引用Jan-Philip Gehrcke回答:

    正如您已經發現的那樣,exists和isfile之間的區別在於前者在給定路徑是目錄或檔案的情況下返回True,而後者僅在路徑指向檔案時返回True。
    從技術角度來看,目錄和檔案非常相似。 檔案可以包含任何型別的資料。
    目錄只是檔案系統中的一個特殊條目(至少在Unix作業系統上它只是一個特殊檔案),表示它可能包含檔案和其他目錄。 它是構建資料結構的有用方法。 使用目錄,您可以按層次結構組織資料。
    特別是在Windows世界中,目錄通常稱為“資料夾”。 我相信你自己正在使用“資料夾”來組織你的檔案。路徑是指向檔案系統中資源的明確指標。 它可以指向檔案或目錄。