Python读取CSV文件,并写入其他跳过列 [英] Python read CSV file, and write to another skipping columns
本文介绍了Python读取CSV文件,并写入其他跳过列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有18列的CSV输入文件 我需要使用输入的所有列(第4列和第5列除外)创建新的CSV文件
I have CSV input file with 18 columns I need to create new CSV file with all columns from input except column 4 and 5
我的功能现在看起来像
def modify_csv_report(input_csv, output_csv):
begin = 0
end = 3
with open(input_csv, "r") as file_in:
with open(output_csv, "w") as file_out:
writer = csv.writer(file_out)
for row in csv.reader(file_in):
writer.writerow(row[begin:end])
return output_csv
因此它读写第0-3列,但我不知道如何跳过第4,5列并从那里继续
So it reads and writes columns number 0 - 3, but i don't know how skip column 4,5 and continue from there
推荐答案
这就是您想要的:
import csv
def remove_csv_columns(input_csv, output_csv, exclude_column_indices):
with open(input_csv) as file_in, open(output_csv, 'w') as file_out:
reader = csv.reader(file_in)
writer = csv.writer(file_out)
writer.writerows(
[col for idx, col in enumerate(row)
if idx not in exclude_column_indices]
for row in reader)
remove_csv_columns('in.csv', 'out.csv', (3, 4))
这篇关于Python读取CSV文件,并写入其他跳过列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文