os.path.isfile(jsonpath) 和 os.path.exists(jsonpath) 兩者的功能有些許不同:
-
os.path.isfile(jsonpath)檢查指定路徑是否指向一個檔案。如果該路徑存在且是一個檔案,則返回True;否則,返回False。這個函式專門用於確認指定路徑是否是一個檔案,而不是目錄或其他類型的檔案。 -
os.path.exists(jsonpath)則檢查指定的路徑是否存在,無論是檔案還是目錄。如果指定的路徑存在,則返回True;否則,返回False。這個函式用於確認路徑是否存在,無論它是一個檔案還是目錄。
code:
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 09 18:08:35 2023
@author: SavingKing
"""
import os
# 假設有一個名為 "testfile.txt" 的檔案以及一個名為 "testdir" 的目錄存在
# 使用 os.path.isfile() 確認檔案是否存在
file_path = r"D:\Temp\testfile.txt"
dir_path = r"D:\Temp\testdir"
# 檢查檔案
if os.path.isfile(file_path):
print(f"{file_path} 存在且是一個檔案")
else:
print(f"{file_path} 不存在或不是檔案")
# 檢查目錄
if os.path.isfile(dir_path):
print(f"{dir_path} 存在且是一個檔案")
else:
print(f"{dir_path} 不存在或不是檔案")
# 使用 os.path.exists() 確認路徑是否存在
# 檢查檔案
if os.path.exists(file_path):
print(f"{file_path} 存在")
else:
print(f"{file_path} 不存在")
# 檢查目錄
if os.path.exists(dir_path):
print(f"{dir_path} 存在")
else:
print(f"{dir_path} 不存在")
輸出結果:

這個程式碼示範了兩個函式的不同行為。os.path.isfile() 僅確認指定的路徑是否為檔案,而 os.path.exists() 則確認路徑是否存在,無論它是檔案還是目錄。根據你的需求,你可以選擇使用其中一個函式。
推薦hahow線上學習python: https://igrape.net/30afN





![Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool_Series] 選取多個rows #bool_Series長度同rows, index也需要同df.index ,可以使用.equals() 確認: df.index.equals(mask.index) Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool_Series] 選取多個rows #bool_Series長度同rows, index也需要同df.index ,可以使用.equals() 確認: df.index.equals(mask.index)](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2025/04/20250420212553_0_6fb2c3.png?quality=90&zoom=2&ssl=1&resize=350%2C233)




近期留言