Python reads each line of a txt file
Reading Each Line of a TXT File with Python
Reading text files is a common operation in Python. This article will explain in detail how to open, read, and process each line of a TXT file using Python.
1. Opening a Text File
To read each line of a TXT file, you first need to open the file. Python provides the built-in open()
function for opening files. The following example code uses the open()
function to open a text file:
file = open("example.txt", "r") <p>In the above code, the parameter <code>"example.txt"
is the file name of the text file to be opened."r"
indicates that the file is opened in read-only mode. By assigning the returned file object to the variablefile
, we can continue to read from it.2. Reading a Text File Line by Line
To read each line of a text file, you can use Python's built-in iterator, the
for
loop. The following example shows this:for line in file: print(line)
The above code reads each line of the file in sequence and prints it. In this way, we can iterate over the entire file and further process each line.
3. Closing the File
After reading the file's contents, you should close the file promptly to release resources. You can use the file object's
close()
method to close the file. An example is as follows:file.close()
In actual development, to avoid forgetting to close a file, you can use the
with
statement to automatically handle file opening and closing. An example is as follows:with open("example.txt", "r") as file: for line in file: print(line)
In the above code, the file is automatically closed after the
with
statement block executes, eliminating the need to manually call theclose()
method.4. Processing Each Line of a Text File
Once we have read the contents of the file line by line, we can further process each line. Here are a few common methods:
4.1 Removing Linefeeds
When reading each line of a text file, it often contains linefeeds. To make processing each line more convenient, we can use the string method strip() to remove the linefeeds. An example is as follows:
with open("example.txt", "r") as file: for line in file: line = line.strip() print(line)
In the above code, the strip() method removes whitespace characters, including linefeeds, from both ends of a string.
4.2 Splitting Each Line
Sometimes, we need to split each line into multiple parts based on a specific delimiter. We can use the string method
split()
to do this. Here's an example:with open("example.txt", "r") as file: for line in file: parts = line.strip().split(",") print(parts)
In the above code,
split(",")
splits each line into multiple parts based on commas and returns a list.4.3 Converting Data Types
When reading each line from a text file, the data type is usually a string. If you need to convert it to another data type, you can use a type conversion function (such as
int()
,float()
, etc.). The following example shows the following:with open("example.txt", "r") as file: for line in file: parts = line.strip().split(",") name = parts[0] age = int(parts[1]) height = float(parts[2]) print(name, age, height)
In the above code,
int()
andfloat()
convert strings to integers and floating-point types, respectively.4.4 Counting Lines
If you need to count the number of lines in a text file, you can introduce a counter in the loop and increment the counter by 1 each time the loop is executed. The following example:
with open("example.txt", "r") as file:
for line in file:
count += 1print("Total number of lines:", count)
In the above code, the
count
variable is used to record the number of lines, with an initial value of 0. Each time through the loop, the counter is incremented by 1. After the loop ends, the total number of lines is printed.The following is a complete example that demonstrates how to read each line of a txt file and process the data in each line.
count = 0 with open("example.txt", "r") as file: for line in file: count += 1 line = line.strip() parts = line.split(",") name = parts[0] age = int(parts[1]) height = float(parts[2]) print("Number", count, "Line:", name, age, height) print("Total number of lines:", count)
Suppose the contents of the
example.txt
file are as follows:Alice, 25, 165.5 Bob, 30, 175.2
The above code will output:
Line 1: Alice 25 165.5 Line 2: Bob 30 175.2 Total Lines: 2
By reading this article, you should have learned how to use Python to read each line of a txt file and process its contents accordingly. In practice, you can further manipulate and analyze the data in each line based on your specific needs.