Python CSV 跳过或删除第二行

1 投票
2 回答
801 浏览
提问于 2025-04-18 00:11

大家好,

这是我需要转换成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 个回答

1

my_text = inputfile.readlines()[63:-8] 这行代码后面加上 del my_text[1]

2

先写上表头,跳过一行,然后再写剩下的行。

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

撰写回答