2014-03-27 180 views
1

全部,Python CSV跳过或删除第二行

这是我需要更改为csv文件的文本文件的片段。

|head1|head2|head3| 
+----+------+-----+ 
|10000|10001|10002| 

所以我用这个python代码把它变成CSV。

#open the input & output files. 
inputfile = open('tr2796h_05.10.txt', 'rb') 
csv_file = r"mycsv1.csv" 
out_csvfile = open(csv_file, 'wb') 

#read in the correct lines 
my_text = inputfile.readlines()[63:-8] 
#convert to csv using | as delimiter 
in_txt = csv.reader(my_text, delimiter = '|') 
#hook csv writer to output file 
out_csv = csv.writer(out_csvfile) 
#write the data 
out_csv.writerows(in_txt) 
#close up 
inputfile.close() 
out_csvfile.close() 

输出是这样的:

,head1,head2,head3, 
,+----+------+-----+, 
,10000,10001,10002, 

如预期。

问题是这样的 - 我该如何删除第二行?

回答

2

编写标题,跳过一行,然后写入其余行。

out_csv.writerow(next(in_txt)) # headers 
next(in_text) # skip 
out_csv.writerows(in_txt) # write remaining 
+0

我相信你错误地抄录了我的第一行。请注意,它是'作家'而不是'作家'。 –

+0

你是在现场。 这是Lonut Hulub的方法低于'首选'做事方式吗? 你能帮我理解两者的好处吗? – TangoAlee

+0

@TangoAlee。 Ionut Hulub的回答是适合你的情况。即使在您不预取数据的情况下,我的答案也可以工作。 –

1

my_text = inputfile.readlines()[63:-8]之后加del my_text[1]

+0

我想给所有人好评! – TangoAlee