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 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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/python-basic-exercise-87.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics