簡體   English   中英

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

[英]Print only lines after certain lines in Python

例如,我有一個包含很多行的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

使用Python中的代碼,我只需要打印某些行之后的行,更具體地說,我需要打印第3行之后的行和第7行之后的行,並且在打印之后,需要將它們放入另一個csv。

我該怎么做? 謝謝!!

如果可以合理地預測行中可能包含的內容,那么使用正則表達式將是我的首選解決方案。

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

該代碼最初將print_following_line設置為False,因為您不知道是否要打印下一行。 如果您的正則表達式字符串與當前行匹配,則print_following_line bool將設置為True。 然后它將打印下一行並將其添加到您的輸出列表中,您以后可以將其寫入CSV。

如果您是regex的新手,那么此網站對調試和測試匹配項非常有用: https//regex101.com/

您可以循環瀏覽文件中的各行,如果找到匹配項,則返回。 像這樣:

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