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


当前回答

你可以使用os模块中的stat()方法。您可以为它提供字符串、字节甚至PathLike对象形式的路径。它也适用于文件描述符。

import os

res = os.stat(filename)

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

其他回答

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

import os

res = os.stat(filename)

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

你需要os.stat返回的对象的st_size属性。你可以使用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

输出以字节为单位。

我们有两个选择,都包括导入os模块

1)

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

作为os.stat()函数返回一个包含许多头文件的对象,包括文件创建时间和最后修改时间等。其中st_size给出了文件的确切大小。 文件路径可以是绝对路径也可以是相对路径。

2) 在这里,我们必须提供准确的文件路径,文件路径可以是相对路径也可以是绝对路径。

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