我有一个带头的CSV文件。要删除csv的前5行,但不删除标题吗?在Python中

2024-04-24 04:45:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个下面的CSV文件,文件头(a,B,C,D):

A,B,C,D
1,2,3,4
2,1,3,5
6,8,0,9
4,7,9,2
2,5,4,9
1,1,7,3
2,9,5,6

删除前5行但不删除标题后,我需要输出:

A,B,C,D
1,1,7,3
2,9,5,6

下面是我的Python代码片段,但无法添加任何保留头的代码:

with open(filename.csv , 'rb') as infile: data_in = infile.readlines()

with open ('temp.csv', 'wb') as outfile: outfile.writelines(data_in[5:])

请帮助我。在我的情况下,标题也是删除,但我想保留标题每次。


Tags: 文件csv代码in标题dataaswith
3条回答

I advise using pandas as it will retain the header and you can perform multiple operations on data with ease. A pandas dataframe can represent 2D data in form of columns and rows similar to a csv file.

将文件加载到pandas数据框中

df = pd.read_csv('file.csv')

然后选择所需的行

df_temp = df.loc[5:]

这里是必需的输出

   A  B  C  D
5  1  1  7  3
6  2  9  5  6

您可以进一步将其写入csv文件

df_temp.to_csv('output.csv',index=False)

怎么样:

with open ('temp.csv', 'wb') as outfile:
    outfile.writelines(data_in[0])
    outfile.writelines(data_in[5:])

您可以使用^{}来避免将整个文件读入内存:

from itertools import islice
import csv

with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)
    csv_output.writerow(next(csv_input))
    csv_output.writerows(islice(csv_input, 5, None))

输出:

A,B,C,D
1,1,7,3
2,9,5,6

首先读取第一行并将其写入输出。然后使用islice()跳过5行,然后将剩余的行传递给writerows()

相关问题 更多 >