How to extract specific lines of data in Python?

To extract data from a specified row, you can use the following method:

  1. Iterate through the rows using a loop, and extract the data of a specified row by its index. For example, if you want to extract data from the 3rd row, you can use the following code:
with open('data.txt', 'r') as file:
    lines = file.readlines()
    specified_line = lines[2]  # 索引从0开始,所以第3行为索引2
    print(specified_line)
  1. list all the items
with open('data.txt', 'r') as file:
    lines = file.readlines()
    specified_lines = [line for line_number, line in enumerate(lines) if 'keyword' in line]
    for line in specified_lines:
        print(line)

Both methods extract based on the number of lines in a text file. If you are working with other data types such as CSV or Excel, you can use the appropriate libraries and methods for extraction.

bannerAds