Python Practice › File Handling Programs › Program 21
Size of a file
Write a Python program to get the size of a file in bytes.
Output
1500 bytes
Approach
os.path.getsize().
Solution
import os with open("data.bin", "wb") as f: f.write(b"x" * 1500) print(os.path.getsize("data.bin"), "bytes")Output
1500 bytes
Line by line
Line 3
Writing in binary mode makes the size exact on every operating system.
Learn the concept
New to this topic? Read the lesson, then come back.