如何删除以“ - ”开头的行加上3行后

问题描述:

我有我的测试数据,看起来像这样。它包括对如何删除以“ - ”开头的行加上3行后

"----------" 

PAGE1 

PARAGRAPH 

EXAMPLE 

example1 

example2 

example3 

example4 

example5 

"----------" 

PAGE2 

PARAGRAPH 

EXAMPLE 

example1 

example2 

example3 

example4 

example5 

目的是除去含

"------" 

PAGE 

PARAGRAPH 

EXAMPLE 

的4行,这样我可以输出的例子的仅有的列表1列.CSV consiting

import csv 
input = open('Test_Parse.csv', 'rb') 
output = open('first_edit.csv', 'wb') 
writer = csv.writer(output) 
for row in csv.reader ('Test_Parse.csv'): 
if not row.startswith ("------"): 
    writer.writerow(row) 
input.close() 
output.close() 

这是试图删除与"------"行但挣扎?

任何帮助或指向正确的方向将不胜感激!

+0

请将我的答案标记为正确,如果它对您有用。 – alexisdevarennes

您可以使用行计数器的一个简单的想法。

  • 在开始的时候,初始化计数器为0
  • 对于每一个你读线:
    • 如果该行是“------”,计数器设置为零。
    • 将计数器增加1
    • 如果计数器为5或更多,则打印该行。

治疗fileobject作为迭代器:

import csv 

with open('Test_Parse.csv', 'r') as inp, open('first_edit.csv', 'w', newline='') as out: 
    writer = csv.writer(out) 
    for l in inp: 
     if l.startswith('"------'): 
      next(inp) # extract the next line from the file to skip 
      next(inp) 
      next(inp) 
     else: 
      writer.writerow((l.strip(),)) 

最终first_edit.csv内容:

example1 
example2 
example3 
example4 
example5 
example1 
example2 
example3 
example4 
example5 

只要你行转换为ITER和呼叫下一个跳过的行你不要。请参阅:

import csv 
input = open('Test_Parse.csv', 'rb') 
output = open('first_edit.csv', 'wb') 
writer = csv.writer(output) 
rows = iter(csv.reader ('Test_Parse.csv')) 
for row in rows: 
    if row.startswith ("------"): 
     next(rows) 
     next(rows) 
     next(rows)  
    else: 
     writer.writerow(row) 
input.close() 
output.close() 

如果我是你,我会做ITER()和next()一些阅读

见例如:RomanPerekhrest答案与(使用https://www.programiz.com/python-programming/iterator

通知)也是情理之中因为您不需要在输入和输出上调用.close()。