Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (1.6k points)

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.

1 Answer

0 votes
by (10.9k points)

@Selena, You can use os.path.getsize(path) which returns the size of the path in bytes.It also raises an OSError in case, the file does not exist or is inaccessible.

import os

path = 'C:\\Python27\\Lib\\genericpath.py'

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

print(stat_info)

Output:

243 

You can also use os.stat(path) method to give the status of the path specified:

Ex-

import os

path = 'C:\\Python27\\Lib\\genericpath.py'

Stat_info = os.stat(path)

print(stat_info)

 

Output:

os.stat_result(st_mode=34188, st_ino=725981, st_dev=2867, st_nlink=1, st_uid=1000,st_gid=1000, st_size=243, st_atime=15315670940, st_mtime=1630306690, st_ctime=15303487690)

Related questions

0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jun 26, 2019 in Python by Anurag (33.1k points)
0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Aug 27, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
asked Aug 23, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

29.3k questions

30.6k answers

501 comments

104k users

Browse Categories

...