Python 取得檔案大小 getsize

本篇介紹 Python 中取得檔案大小 os.path.getsize 的用法與範例。
以下範例是在 Python 3 環境下測試過。

使用範例

在 Python 中要取得檔案大小可用 os.path.getsize()
getsize 會返回檔案大小,單位為bytes,如果檔案不存在就返回錯誤,
使用 os.path.getsize 時,需先 import os

程式碼如下:

python-os-path-getsize.py
1
2
3
4
5
6
7
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os

path = 'file.txt'
size = os.path.getsize(path)
print('%s = %d bytes' % (path, size))

輸出結果如下:

1
file.txt = 383 bytes

範例2

使用 getsize 如果不想要前面加 os.path 這麼長的的話,可以用下面這種寫法:

1
2
3
4
5
6
7
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from os.path import getsize

path = 'file.txt'
size = getsize(path)
print('%s = %d bytes' % (path, size))

參考
Python os.path() 模块 | 菜鸟教程
https://www.runoob.com/python/python-os-path.html
Python | os.path.size() method - GeeksforGeeks
https://www.geeksforgeeks.org/python-os-path-size-method/
os.path.getsize — Common pathname manipulations — Python 3 documentation
https://docs.python.org/3/library/os.path.html#os.path.getsize

其它相關文章推薦
Python 判斷檢查檔案是否存在 os.path.isfile
Python 判斷資料夾是否存在 os.path.isdir
Python 判斷檢查路徑是否存在 exists
Python 去除空白與去除特殊字元 strip
Python 取出檔案名稱 basename
Python 取出目錄的路徑 dirname
Python 字串分割 split
Python 連接字串 join
Python 去除空白與去除特殊字元 strip