Introduction
In the world of programming, text files are a common medium for storing and sharing data. Whether it’s a log file, a configuration file, or just a simple document, being able to manipulate and analyze text files is an essential skill for any programmer. One fundamental task when working with text files is counting the number of lines they contain. In this article, we’ll walk through the process of writing a Python program to count the number of lines in a text file.
Getting Started
Before we dive into coding, let’s break down the steps we’ll take to accomplish this task:
- Open the File: We’ll start by opening the text file in Python using the `open()` function.
- Read the Lines: Once the file is open, we’ll read its contents line by line using a loop.
- Counting Lines: For each line (non-empty lines) we read, we’ll increment a counter to keep track of the number of lines.
- Display the Count: Finally, we’ll display the total count of lines in the text file.
Writing the Code
Let’s turn these steps into Python code:
def count_lines(file_name):
try:
with open(file_name, 'r') as file:
line_count = 0
content = file.read()
content = content.split("n")
for line in content:
# Checking if the line is empty
if line:
line_count += 1
return line_count
except FileNotFoundError:
print("File not found.")
return -1 # Return -1 to indicate an error
if __name__ == "__main__":
file_name = input("Enter the name of the text file: ")
lines = count_lines(file_name)
if lines >= 0:
print(f"The file '{file_name}' contains {lines} lines.")
Understanding the Code
- The `count_lines()` function takes a filename as an argument.
- We use a `try` block to catch any potential `FileNotFoundError` that might occur if the specified file does not exist.
- Within the `with open()` block, we use a `for` loop to iterate through each line in the file. The loop increments the `line_count` for each non-empty line encountered.
- After the loop completes, the function returns the `line_count`.
- In the` __main__` block, we take user input for the file name.
- We call the `count_lines()` function with the provided file name and store the returned value in the `lines` variable.
- If the value of `lines` is greater than or equal to 0, we display the total number of lines in the file. Otherwise, we display an error message.
Running the Program
- Save the code in a `.py` file (e.g., `line_counter.py`).
- Place the text file you want to count lines for in the same directory as the Python script.
- Open a terminal and navigate to the directory where the script is located.
- Run the script using the command: `python line_counter.py`.
- Follow the prompts to enter the name of the text file.
- The program will display the total number of lines in the specified text file.
Conclusion
In this article, we’ve walked through the process of creating a simple Python program to count the number of lines in a text file. This basic task is a building block for more complex text file processing and analysis. As you continue your programming journey, you’ll find that Python’s simplicity and versatility make it a great choice for handling various file-related tasks.