Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting file size in Python? [duplicate]

Tags:

python

file

size

Is there a built-in function for getting the size of a file object in bytes? I see some people do something like this:

def getSize(fileobject):     fileobject.seek(0,2) # move the cursor to the end of the file     size = fileobject.tell()     return size  file = open('myfile.bin', 'rb') print getSize(file) 

But from my experience with Python, it has a lot of helper functions so I'm guessing maybe there is one built-in.

like image 899
6966488-1 Avatar asked Jul 06 '11 05:07

6966488-1


People also ask

How do you get the size of a file using Python?

Use os.path.getsize() function Use the os. path. getsize('file_path') function to check the file size. Pass the file name or file path to this function as an argument.

How does Python compare files in size?

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


1 Answers

Use os.path.getsize(path) which will

Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.

import os os.path.getsize('C:\\Python27\\Lib\\genericpath.py') 

Or use os.stat(path).st_size

import os os.stat('C:\\Python27\\Lib\\genericpath.py').st_size  

Or use Path(path).stat().st_size (Python 3.4+)

from pathlib import Path Path('C:\\Python27\\Lib\\genericpath.py').stat().st_size 
like image 196
Artsiom Rudzenka Avatar answered Sep 20 '22 08:09

Artsiom Rudzenka