5.Write a Program to count number of lines in a text file
#-------------------------
import os
file_name = "sample_data.txt"
content = "Line 1: Machine Learning\nLine 2: Data Science\nLine 3: Computer Vision\nLine 4: Natural Language Processing"
with open(file_name, "w") as f:
f.write(content)
def count_lines(filename):
try:
with open(filename, 'r') as file:
line_count = 0
for line in file:
line_count += 1
return line_count
except FileNotFoundError:
return "Error: The file was not found."
total_lines = count_lines(file_name)
print(f"The file '{file_name}' has {total_lines} lines.")