當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python os.path.size()用法及代碼示例

Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。 os.path模塊是Python中OS模塊的子模塊,用於通用路徑名操作。

os.path.getsize()Python中的方法用於檢查指定路徑的大小。它以字節為單位返回指定路徑的大小。如果文件不存在或無法訪問,則引發OSError。

用法: os.path.getsize(path)

參數:
path:代表文件係統路徑的path-like對象。 path-like對象是表示路徑的字符串或字節對象。

返回類型:此方法返回一個整數值,該整數值表示指定路徑的大小(以字節為單位)。

代碼1:使用os.path.getsize()方法

# Python program to explain os.path.getsize() method  
    
# importing os module  
import os 
  
# Path 
path = '/home/User/Desktop/file.txt'
  
# Get the size (in bytes) 
# of specified path  
size = os.path.getsize(path) 
  
  
# Print the size (in bytes) 
# of specified path  
print("Size (In bytes) of '%s':" %path, size)
輸出:
Size (In bytes) of '/home/User/Desktop/file.txt': 243

代碼2:使用os.path.getsize()方法時的處理錯誤

# Python program to explain os.path.getsize() method  
    
# importing os module  
import os 
  
# Path 
path = '/home/User/Desktop/file2.txt'
  
# Get the size (in bytes) 
# of specified path  
try : 
    size = os.path.getsize(path) 
  
except OSError : 
    print("Path '%s' does not exists or is inaccessible" %path) 
    sys.exit() 
  
# Print the size (in bytes) 
# of specified path  
print("Size (In bytes) of '% s':" % path, size)
輸出:
Path '/home/User/Desktop/file2.txt' does not exists or is inaccessible

參考: https://docs.python.org/3/library/os.path.html



相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.path.size() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。