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()處理雙維度資料,dict跟2D list轉為DataFrame有何差別?如何用index及columns屬性客製化index跟欄位名稱?df.index = [“一”,”二”,”三”,”四”] ; df.columns = 使用.head(n) ; .tail(m) ;取首n列,尾m列; .at[index,欄位名稱] 取單一資料 ; .iat[index,欄位順序] 取單一資料 ; .loc[index,欄位名稱] 取資料 ; .iloc[index,欄位順序];df.iloc[ [0,1],[0,2]])取資料 ; df.iloc[ 0:3,0:2]切片 Python: pandas.DataFrame()處理雙維度資料,dict跟2D list轉為DataFrame有何差別?如何用index及columns屬性客製化index跟欄位名稱?df.index = [“一”,”二”,”三”,”四”] ; df.columns = 使用.head(n) ; .tail(m) ;取首n列,尾m列; .at[index,欄位名稱] 取單一資料 ; .iat[index,欄位順序] 取單一資料 ; .loc[index,欄位名稱] 取資料 ; .iloc[index,欄位順序];df.iloc[ [0,1],[0,2]])取資料 ; df.iloc[ 0:3,0:2]切片](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2022/11/20221111093547_79.png?quality=90&zoom=2&ssl=1&resize=350%2C233)



近期留言