如果它包含特定的单词,我如何从csv中删除这些行?

时间:2017-07-21 10:10:47

标签: python csv text

我有一个看起来像这样的CSV文件:

"Estimated 10:10 AM
"	"10:40 AM	KL1973	
"	"Amsterdam (AMS)
"	"KLM	B738 (PH-BXB)	
"
"Scheduled
"	"10:50 AM	AY753	
"	"Helsinki (HEL)
"	"Finnair	A321 (OH-LZL)	
"
"Estimated 10:49 AM
"	"10:50 AM	W62282	
"	"Brussels (CRL)
"	"Wizz Air	A321 (HA-LXS)	
"
"Scheduled
"	"10:50 AM	OS713	
"	"Vienna (VIE)
"	"Austrian Airlines	DH8D (OE-LGL)	
"
"Scheduled
"	"11:00 AM	W62272	
"	"Eindhoven (EIN)
"	"Wizz Air	A321 (HA-LXQ)	
"

如果包含单词“Scheduled”,我想知道如何删除一行?

我尝试使用类似的东西,但它不起作用(Python 2.7)。没有错误消息,它正在运行但什么都不做:

import urllib2
import unicodecsv as csv
import os
import sys
import io
import time
import datetime
import pandas as pd
from bs4 import BeautifulSoup
import sys
import re

def to_2d(l,n):
    return [l[i:i+n] for i in range(0, len(l), n)]
 
f = open('air.txt', 'r')
x = f.readlines()

filename=r'output.csv'

resultcsv=open(filename,"wb")
output=csv.writer(resultcsv, delimiter=';',quotechar = '"', quoting=csv.QUOTE_NONNUMERIC, encoding='latin-1')
 
maindatatable = to_2d(x, 4)
print maindatatable
output.writerows(maindatatable)

resultcsv.close()

open("output.csv", "r+") as f:
t = f.read() to_delete = '"Scheduled'
   f.seek(0) for line in t.split('\n'):
   if line != to_delete:
      f.write(line + '\n') f.truncate()
   
还有一个问题。 如何删除此csv文件中的前3行和后3行?

对不起,如果这看起来像一个非常简单的问题,但我是python的新手,非常感谢这方面的任何帮助,谢谢!!

1 个答案:

答案 0 :(得分:0)

你没有像我一样编写你的代码:你不尊重身份,你没有在开放前放置“带”字(文件......

请用此更新:

>  with open("file.csv", "r+") as f:
>     t = f.read()
>     to_delete = '"Scheduled'
>     f.seek(0)
>     for line in t.split('\n'):
>         if line != to_delete:
>             f.write(line + '\n')
>     f.truncate()