简体   繁体   English

在Python中的某些行之后仅打印行

[英]Print only lines after certain lines in Python

I have a csv file with lots of lines, for example 例如,我有一个包含很多行的csv文件

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. 使用Python中的代码,我只需要打印某些行之后的行,更具体地说,我需要打印第3行之后的行和第7行之后的行,并且在打印之后,需要将它们放入另一个csv。

How can I do it? 我该怎么做? Thanks!! 谢谢!!

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. 该代码最初将print_following_line设置为False,因为您不知道是否要打印下一行。 If your regex string matches the current line, your print_following_line bool will be set to True. 如果您的正则表达式字符串与当前行匹配,则print_following_line bool将设置为True。 It will then print the next line and add it to your output list which you can write to a CSV later. 然后它将打印下一行并将其添加到您的输出列表中,您以后可以将其写入CSV。

If you are new to regex, this website is incredibly helpful for debugging and testing matches: https://regex101.com/ 如果您是regex的新手,那么此网站对调试和测试匹配项非常有用: https//regex101.com/

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM