There are different methods to get the size of a file in python and this article explains 3 of those methods with examples.
Finding out a file size becomes important when you want to monitor a particular file for a size limit or when you want to order files in a directory based on their size.
Python’s
os.path
module provides a getsize
function which takes a file path as argument and returns the size of file in bytes.Example,
import os # get the size of file size = os.path.getsize('f:/file.txt') print('Size of file is', size, 'bytes')
Above code produces the following output
Size of file is 760 bytes
Python’s
os
module provides a stat
function which takes a path as argument. This path may be a string or a path object and returns a structure containing statistical details about the path supplied. This structure has many properties out of which, st_size
property contains the size of the file(in bytes) present at the supplied path.
Example,
import os # get file stats stats = os.stat('f:/file.txt') print('Size of file is', stats.st_size, 'bytes')
Output of this code is as below
Size of file is 760 bytes
os.stats
function, then you will get something like this.os.stat_result(st_mode=33206, st_ino=562949953421562, st_dev=101961010, st_nlink=1, st_uid=0, st_gid=0, st_size=760, st_atime=1554137744, st_mtime=1554137744, st_ctime=1503555351)
Notice that it has an
st_size
property.Method 3: Using file object
Open the file whose size needs to be determined using open
function and assign the returned object to a variable. The returned object acts as a handle to the file and can be used for various file handling operations.
Learn how to read a file in python here.
Once we get the object pointing to the file, following steps need to be taken to find out a file size using this method.
- Initially when the file is opened, the file cursor points to the beginning of the file. File object has a
seek
method which is used to set the cursor to a desired location.
It accepts 2 arguments, first is the start location and second is the end location at which the cursor will be placed.
If the first argument is not supplied, then it defaults to 0, meaning the beginning of file. - Set the cursor to the end of the file using
seek
method supplying it 0 as the start value andos.SEEK_END
as the end value whereSEEK_END
is a constant isos
module and marks the end of file. - File object has a
tell
method which returns the current position of the cursor. This is the number of bytes that the cursor has moved. - Thus, when you position the file cursor to the end of the file,
tell
method will actually return the number of bytes in the file which is also the size of the file.
Example,
# open file for reading f = open('f:/file.txt') # move file cursor to end f.seek(0, os.SEEK_END) # get the current cursor position print('Size of file is', f.tell(), 'bytes')
Output of this code is
Size of file is 760 bytes
Hope this post will help you in calculating file size using python.