Python: Get the size of a file
File Size Finder
Write a Python program to get the size of a file.
Sample Solution-1:
Python Code:
# Import the os module for file operations.
import os
# Get the size of the file "abc.txt".
file_size = os.path.getsize("abc.txt")
# Print the size of the file "abc.txt" in bytes.
print("\nThe size of abc.txt is:", file_size, "Bytes")
# Print a newline character for spacing.
print()
Sample Output:
The size of abc.txt is : 0 Bytes
Sample Solution-2:
Python Code:
# Import the os module for file operations.
# Get the file information for 'main.py' using os.stat().
file_size = os.stat('main.py')
# Print the size of the file 'main.py' in bytes using the st_size attribute.
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 the os module for file operations.
# Open the file 'main.py' in default read mode.
file = open('main.py')
# Move the file cursor to the end of the file using file.seek().
file.seek(0, os.SEEK_END)
# Print the current position of the file cursor, which represents the size of the file.
print("The size of main.py is:", file.tell(), "bytes")
Sample Output:
The size of main.py is : 117 bytes
Python Code Editor :
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 Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics