To get the length of a file, or the number of lines in a file, you can use the Python readlines() and len() functions.
with open("example.txt","r") as f:
print(len(f.readlines()))
#Output:
101
When working with files, the ability to get different statistics about the file easily can be useful.
One such statistic is the length of a file. The length of a file is the number of lines in a given file.
We can get all lines in a file with the readlines() function, and then use the len() function to get the number of lines in the file.
Below is a simple example showing you how to get the length of a file in Python.
with open("example.txt","r") as f:
print(len(f.readlines()))
#Output:
101
How to Get File Size Using Python
Another common statistic, which may be helpful to know how to get, is the size of a file in bytes.
The Python os module has many great functions which help us interact with the operating system of our computer.
To get the size of a file in Python, you can use the os.path module getsize() function. getsize() returns the size of the file in bytes.
Below is a simple example showing how you can get the size of a file using Python.
import os
print(os.path.getsize("C:/Users/TheProgrammingExpert/example.png"))
#Output:
351
Hopefully this article has been useful for you to learn how to get the length of a file using Python.