python删除csv某一列
作者:野牛程序员:2023-07-24 08:01:40python阅读 2921
在 Python 中删除 CSV 文件中的某一列可以通过以下步骤完成:
读取 CSV 文件并解析数据。
删除目标列。
将更新后的数据写回到 CSV 文件。
假设要删除名为 "column_to_delete" 的列,以下是一种实现方式:
import csv def remove_column_from_csv(input_file, output_file, column_to_delete): with open(input_file, 'r', newline='') as input_csvfile: with open(output_file, 'w', newline='') as output_csvfile: reader = csv.DictReader(input_csvfile) fieldnames = [field for field in reader.fieldnames if field != column_to_delete] writer = csv.DictWriter(output_csvfile, fieldnames=fieldnames) writer.writeheader() for row in reader: del row[column_to_delete] writer.writerow(row) if __name__ == "__main__": input_file_path = 'input.csv' # 指定输入文件路径 output_file_path = 'output.csv' # 指定输出文件路径 column_to_delete = 'column_to_delete' # 要删除的列的名称 remove_column_from_csv(input_file_path, output_file_path, column_to_delete)
在上述代码中,使用 csv.DictReader 读取 CSV 文件,并使用 csv.DictWriter 写入数据。DictReader 和 DictWriter 是基于字典的 CSV 文件读写器,可以按列名访问和写入数据。
请注意,在实际操作中,输入文件路径和输出文件路径应该根据实际情况进行调整。执行这段代码后,output.csv 文件将会是一个删除了指定列的新 CSV 文件。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

