How to loop through and read the contents of a file in Python?

In Python, you can loop through a file’s contents using the open() function and the readlines() method. The specific steps are as follows:

  1. to unlock
  2. retrieve a list of all lines from a text file
  3. Traverse the list and process the content of each line in a loop.

Here is an example code:

with open('filename.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        # 处理每一行的内容
        print(line)

The code above opens a file named ‘filename.txt’ using the statement with open(‘filename.txt’, ‘r’) as file: and assigns the file object to a variable named file. The method file.readlines() reads the contents of the file as a list and assigns it to a variable named lines. It then uses a for loop to iterate through the lines list and processes the content of each line (in this example, it prints the content of each line using the print() function).

Please remember to use the “with” statement to automatically close the file after using it.

bannerAds