在 Python 中删除 CSV 文件中的某一列可以通过以下步骤完成:
读取 CSV 文件并解析数据。
删除目标列。
将更新后的数据写回到 CSV 文件。
假设要删除名为 "column_to_delete" 一肖一码100%准确澳门天天 的列,以下是一种实现方式:
Python
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 文件,并使用 一肖中特免费公开资料15年图1一 写入数据。 和 是基于字典的 CSV 文件读写器,可以按列名访问和写入数据。
请注意,在实际操作中,输入文件路径和输出文件路径应该根据实际情况进行调整。执行这段代码后, 文件将会是一个删除了指定列的新 CSV 文件。