1

I have a csv file with lots of lines, for example

This is line 1
This is line 2 
This is line 3 
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9

And with a code in Python I need to print only lines that come after certain lines, more specifically, I need to print the line that comes after line 3 and the line that comes after line 7, and after printing, need to put them in another csv.

How can I do it? Thanks!!

Ally
  • 129
  • 8
  • 1
    Possible duplicate of [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – Sers Apr 15 '19 at 18:10

2 Answers2

1

If you can reasonably predict what your lines might contain, using regex would be my go-to-solution.

import re

re_pattern = re.compile(r"This is line [37]")
# The above is used to match "This is line " exactly, followed by either a 3 or a 7.
# The r before the quotations mean the following string should be interpreted literally.

output_to_new_csv = []
print_following_line = False
for line in csv_lines:
    if print_following_line:
        print(line)
        output_to_new_csv.append(line)
    print_following_line = False
    if re.match(re_pattern, line):
        print_following_line = True

# Then write output to your new CSV

The code initially sets print_following_line to False since you don't know if you want print the next line. If your regex string matches the current line, your print_following_line bool will be set to True. It will then print the next line and add it to your output list which you can write to a CSV later.

If you are new to regex, this website is incredibly helpful for debugging and testing matches: https://regex101.com/

SyntaxVoid
  • 2,501
  • 2
  • 15
  • 23
1

You can just loop through the lines in the file and return if you find a match. Something like this:

def find_line_after(target):
    with open('lines.csv', 'r') as f:
        line = f.readline().strip()
        while line:
            if line == target:
                return f.readline().strip()
            line = f.readline().strip()
Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169