如何从csv或txt文件中删除标头?

时间:2019-05-20 02:33:53

标签: python csv

我选择了csv的特定列并将其转换为txt。

选定的列名称为“ id”(标题) 而且我不知道如何从txt中删除该“ id”。

这是我的代码。

import csv
with open('garosu_example.csv') as file:
    reader = csv.reader(file)

input_file = "garosu_example.csv"
output_file = "garosu_example.txt"

id = ['id']
selected_column_index = []

with open(input_file, 'r', newline='') as csv_in_file:
    with open(output_file, 'w', newline='/n') as csv_out_file:
        freader = csv.reader(csv_in_file)
        fwriter = csv.writer(csv_out_file)
        header = next(freader)
        for index_value in range(len(header)):
            if header[index_value] in id:
                selected_column_index.append(index_value)
        print(id)
        fwriter.writerow(id)
        for row_list in freader:
            row_list_output = []
            for index_value in selected_column_index:
                row_list_output.append(row_list[index_value])
            print(row_list_output)
            f.writer.writerow(row_list_output)

如何从txt文件中删除“ id”(标题)?

如果我删除csv中的标头,则输出txt文件为空T_T

Here is an example of my csv file

3 个答案:

答案 0 :(得分:1)

您可以跳过第一行,然后将文档替换为所有内容:

with open(file) as f:
    with open("file_without_header.csv",'w') as nh:
        next(f)
        for l in f:
            nh.write(l)

答案 1 :(得分:1)

使用readlineswritelines的另一种方式:

with open('filename.csv') as f:
    with open('no_header.csv', 'w') as f2:
        f2.writelines(f2.readlines()[1:])

答案 2 :(得分:1)

您可以尝试的另一种方法是使用熊猫来操作csv文件。

使用熊猫操纵csv文件的示例为

java.lang.StringIndexOutOfBoundsException

希望有帮助。