w3resource

Python: Get the size of a file

Python Basic: Exercise-87 with Solution

Write a Python program to get the size of a file.

Sample Solution-1:

Python Code:

import os
file_size = os.path.getsize("abc.txt")
print("\nThe size of abc.txt is :",file_size,"Bytes")
print()

Sample Output:

The size of abc.txt is : 0 Bytes

Sample Solution-2:

Python Code:

import os
file_size = os.stat('main.py')
print("\nThe size of abc.txt is :",file_size.st_size,"Bytes")

Sample Output:

The size of abc.txt is : 104 Bytes

Sample Solution-3:

Python Code:

import os
file = open('main.py')
file.seek(0, os.SEEK_END)
print("The size of main.py is :", file.tell(), "bytes")

Sample Output:

The size of main.py is : 117 bytes

Python Code Editor :

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to get the ASCII value of a character.
Next: Given variables x=30 and y=20, write a Python program to print "30+20=50".

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Unpack variables from iterable:

# One can unpack all iterables (tuples, list etc)
>>> a, b, c = 1, 2, 3
>>> a, b, c
(1, 2, 3)

>>> a, b, c = [1, 2, 3]
>>> a, b, c
(1, 2, 3)