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


当前回答

严格地坚持这个问题,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>

其他回答

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

严格地坚持这个问题,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>
#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 ....

我们有两个选择,都包括导入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.path.getsize:

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

输出以字节为单位。