Python Program - Get Line Count of a File
tfigi.wwwidea.com
Here's a Python program to get the line count of a file:
def get_line_count(filename):
with open(filename, 'r') as file:
line_count = 0
for line in file:
line_count += 1
return line_count
# Example usage
filename = 'example.txt'
line_count = get_line_count(filename)
print(f'The file {filename} has {line_count} lines.')
In this program, we define a function get_line_count that takes a filename as input and returns the number of lines in the file.
We open the file using with open(filename, 'r') as file: which automatically closes the file when the with block is exited. We initialize the line_count variable to 0, and use a for loop to iterate through each line in the file. For each line, we increment the line_count variable by 1. Finally, we return the line_count.
To use the function, we simply call it with the filename as input, and print the result.
