簡體   English   中英

Python如何查看文件大小?

[英]How do I check file size in Python?

如何獲取 Python 中文件的大小?

使用os.path.getsize

>>> import os
>>> b = os.path.getsize("/path/isa_005.mp3")
>>> b
2071611

輸出以字節為單位。

您需要st_size的財產返回的對象os.stat 您可以通過使用pathlib (Python 3.4+) 來獲取它:

>>> from pathlib import Path
>>> Path('somefile.txt').stat()
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> Path('somefile.txt').stat().st_size
1564

或使用os.stat

>>> import os
>>> os.stat('somefile.txt')
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> os.stat('somefile.txt').st_size
1564

輸出以字節為單位。

其他答案適用於真實文件,但如果您需要適用於“類文件對象”的東西,請嘗試以下操作:

# f is a file-like object. 
f.seek(0, os.SEEK_END)
size = f.tell()

在我有限的測試中,它適用於真實文件和 StringIO。 (Python 2.7.3。)當然,“類文件對象”API 並不是一個嚴格的接口,但API 文檔建議類文件對象應該支持seek()tell()

編輯

這與os.stat()之間的另一個區別是,即使您沒有讀取文件的權限,您也可以stat()一個文件。 顯然,除非您有閱讀權限,否則搜索/告訴方法將不起作用。

編輯 2

在喬納森的建議下,這是一個偏執版本。 (上面的版本將文件指針留在文件的末尾,所以如果你試圖從文件中讀取,你會得到零字節!)

# f is a file-like object. 
old_file_position = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(old_file_position, os.SEEK_SET)
import os


def convert_bytes(num):
    """
    this function will convert bytes to MB.... GB... etc
    """
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)
        num /= 1024.0


def file_size(file_path):
    """
    this function will return the file size
    """
    if os.path.isfile(file_path):
        file_info = os.stat(file_path)
        return convert_bytes(file_info.st_size)


# Lets check the file size of MS Paint exe 
# or you can use any file path
file_path = r"C:\Windows\System32\mspaint.exe"
print file_size(file_path)

結果:

6.1 MB

使用pathlib在 Python 3.4 中添加或在PyPI 上可用的向后移植):

from pathlib import Path
file = Path() / 'doc.txt'  # or Path('./doc.txt')
size = file.stat().st_size

這實際上只是一個圍繞os.stat的接口,但使用pathlib提供了一種訪問其他文件相關操作的簡單方法。

如果我想從bytes轉換為任何其他單位,我會使用一個bitshift技巧。 如果你右移10你基本上是按一個順序(多個)移動它。

示例: 5GB are 5368709120 bytes

print (5368709120 >> 10)  # 5242880 kilobytes (kB)
print (5368709120 >> 20 ) # 5120 megabytes (MB)
print (5368709120 >> 30 ) # 5 gigabytes (GB)

嚴格堅持這個問題,Python 代碼(+ 偽代碼)將是:

import os
file_path = r"<path to your file>"
if os.stat(file_path).st_size > 0:
    <send an email to somebody>
else:
    <continue to other things>

我們有兩個選項都包括導入 os 模塊

1)

import os
os.stat("/path/to/file").st_size

因為os.stat()函數返回一個對象,該對象包含如此多的頭文件,包括文件創建時間和最后修改時間等。其中st_size給出了文件的確切大小。 文件路徑可以是絕對的,也可以是相對的。

2) 在這里,我們必須提供確切的文件路徑,文件路徑可以是相對的也可以是絕對的。

import os
os.path.getsize("path of file")

您可以使用os模塊中的stat()方法。 您可以為它提供字符串、字節甚至 PathLike 對象形式的路徑。 它也適用於文件描述符。

import os

res = os.stat(filename)

res.st_size # this variable contains the size of the file in bytes
#Get file size , print it , process it...
#Os.stat will provide the file size in (.st_size) property. 
#The file size will be shown in bytes.

import os

fsize=os.stat('filepath')
print('size:' + fsize.st_size.__str__())

#check if the file size is less than 10 MB

if fsize.st_size < 10000000:
    process it ....

您可以使用以下命令檢查文件大小

import sys
print(sys.getsizeof(your_file))

例如,

nums = range(10000)
squares = [i**2 for i in nums]
print(sys.getsizeof(squares))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM