如何在Python中获取文件的大小?


当前回答

使用os.path.getsize:

>>> import os
>>> os.path.getsize("/path/to/file.mp3")
2071611

输出以字节为单位。

其他回答

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
#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 ....

严格地坚持这个问题,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模块中的stat()方法。您可以为它提供字符串、字节甚至PathLike对象形式的路径。它也适用于文件描述符。

import os

res = os.stat(filename)

res.st_size # this variable contains the size of the file in bytes

使用os.path.getsize:

>>> import os
>>> os.path.getsize("/path/to/file.mp3")
2071611

输出以字节为单位。