我有一个看起来像这样的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()
对不起,如果这看起来像一个非常简单的问题,但我是python的新手,非常感谢这方面的任何帮助,谢谢!!
答案 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()