Python os.path.isfile() 方法



os.path 模組中的 isfile(path) 方法用於確定給定的路徑名是否為現有的常規檔案路徑名。此方法遵循符號連結,因此它可以對指向常規檔案的符號連結返回 True。

在處理檔案路徑時,此方法很有用,可以確保提供的路徑恰好是現有的檔案路徑,而不是目錄或無效路徑。

語法

以下是該方法的語法:

os.path.isfile(path)

引數

以下是其引數的詳細資訊:

  • path: 此引數表示路徑類物件,可以是表示檔案系統路徑的字串或位元組物件,也可以是實現了“os.PathLike”協議的物件。

返回值

該方法返回一個布林值,True 表示提供的路徑名“path”是現有的常規檔案。而False 表示給定的路徑不是常規檔案,例如目錄或檔案不存在。

示例

讓我們探索一些示例,以瞭解 os.path.isfile() 方法的工作原理。

示例

以下示例使用 os.path.isfile() 方法來確定給定的路徑名“D:/MyFile.txt”是絕對路徑名還是相對路徑名。

# Import the os module
import os

# Define the path
path = 'D:/MyFile.txt'

# Check if the path is absolute
is_file = os.path.isfile(path)

# Print the result
if is_file:
    print(f'The given path: {path} is an existing regular file:', )
else:
    print(f"The given path: '{path}' does not point to an existing regular file or is not a file.")

輸出

執行上述程式碼後,您將獲得以下輸出:

The given path: 'D:/MyFile.txt' does not point to an existing regular file or is not a file.

示例

在此示例中,以下路徑名“mydir/../myfile.txt”被傳遞給 os.path.isfile() 方法,以確定它是否為現有的常規檔案路徑名。

# Import the os module
import os

# Define the path
path = 'mydir/../myfile.txt'

# Check if the path is absolute
is_file = os.path.isfile(path)

# Print the result
if is_file:
    print(f'The given path: {path} is an existing regular file:', )
else:
    print(f"The given path: '{path}' does not point to an existing regular file or is not a file.")

輸出

在我們的線上編譯器中執行上述程式碼後,將獲得以下輸出:

The given path: 'mydir/../myfile.txt' does not point to an existing regular file or is not a file.

示例

此示例使用 os.path.isfile() 方法和 __file__ 屬性來檢查當前指令碼檔案路徑名是否為有效的路徑。

# Import the os module
import os

# Define the path
path = __file__

# Check if the path is absolute
is_file = os.path.isfile(path)

# Print the result
if is_file:
    print(f'The given path: {path} is an existing regular file:', )
else:
    print(f"The given path: '{path}' does not point to an existing regular file or is not a file.")

輸出

在我們的線上編譯器中執行上述程式碼後,將獲得以下輸出:

The given path: /home/cg/root/66260f4adb57d/main.py is an existing regular file.
os_path_methods.htm
廣告