5YrsLaterDBA
5YrsLaterDBA

Reputation: 34820

How do I check file size in Python?

How do I get the size of a file in Python?

Upvotes: 1193

Views: 1097525

Answers (11)

Mark E. Haase
Mark E. Haase

Reputation: 26931

The other answers work for real files, but if you need something that works for "file-like objects" (e.g. a StringIO), try this:

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

Caveat #1:

The "file-like object" API isn't a rigorous interface but the API documentation suggests that file-like objects should support seek() and tell(), but you should verify this yourself for whatever class you're using.

Caveat #2:

This assumes that the current file position is at the beginning of the file. E.g. if you had already read N bytes from an M-byte file, then this technique would report the size as (M-N). If you don't care about file position at all, you could simplify the 3 lines above to just size = f.seek(0, os.SEEK_END).

Caveat #3:

One important difference between this and os.stat() is that you can stat() a file even if you don't have permission to read it. Obviously the seek() approach won't work unless you have read permission.

Upvotes: 152

Mujeeb Ishaque
Mujeeb Ishaque

Reputation: 2731

Here's another self-explanatory example. With this, bytes will be converted into MBs, GBs, or TBs automatically.

from pathlib import Path
from psutil._common import bytes2human

def get_readable_filesize(text_file: Path):
    return bytes2human(text_file.stat().st_size)

if __name__ == '__main__':
    current_file = Path(__file__).parent.resolve()
    print(get_readable_filesize(current_file / 'file.txt'))

Upvotes: 0

danben
danben

Reputation: 83310

Use os.path.getsize:

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

The output is in bytes.

Upvotes: 1538

gunarevuri
gunarevuri

Reputation: 435

we have two options Both include importing os module

1)

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

as os.stat() function returns an object which contains so many headers including file created time and last modified time etc.. among them st_size gives the exact size of the file. File path can be either absolute or relative.

2) In this, we have to provide the exact file path, File path can be either relative or absolute.

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

Upvotes: 18

krishnakeshan
krishnakeshan

Reputation: 1280

You can use the stat() method from the os module. You can provide it with a path in the form of a string, bytes or even a PathLike object. It works with file descriptors as well.

import os

res = os.stat(filename)

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

Upvotes: 0

Adam Rosenfield
Adam Rosenfield

Reputation: 400562

You need the st_size property of the object returned by os.stat. You can get it by either using 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

or using 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

Output is in bytes.

Upvotes: 1089

user1767754
user1767754

Reputation: 25154

There is a bitshift trick I use if I want to to convert from bytes to any other unit. If you do a right shift by 10 you basically shift it by an order (multiple).

Example: 5GB are 5368709120 bytes

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

Upvotes: 30

Victor Barrantes
Victor Barrantes

Reputation: 2318

Strictly sticking to the question, the Python code (+ pseudo-code) would be:

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>

Upvotes: 9

Michael Mulich
Michael Mulich

Reputation: 1282

Using pathlib (added in Python 3.4 or a backport available on PyPI):

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

This is really only an interface around os.stat, but using pathlib provides an easy way to access other file related operations.

Upvotes: 69

Jacob
Jacob

Reputation: 2434

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

Upvotes: -3

Rajiv Sharma
Rajiv Sharma

Reputation: 7142

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)

Result:

6.1 MB

Upvotes: 112

Related Questions