首页 > 解决方案 > 如何从 csv 或 txt 文件中删除标题?

问题描述

我选择了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'(header)?

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

这是我的 csv 文件的示例

标签: pythoncsv

解决方案


readlines和的另一种方式writelines

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

推荐阅读