如何用python删除csv文件中的某一列?代码该如何编写
发布网友
发布时间:2022-04-29 18:32
我来回答
共1个回答
热心网友
时间:2022-04-18 16:37
如果问题很单纯,甚至连 csv 都可以不使用:
with open('old.csv') as reader, open('new.csv', 'w') as writer:
for line in reader:
items = line.strip().split()
print(' '.join(items[:2]+items[3:]), file=writer)
写个 general 的:
import csv
def del_cvs_col(fname, newfname, idxs, delimiter=' '):
with open(fname) as csvin, open(newfname, 'w') as csvout:
reader = csv.reader(csvin, delimiter=delimiter)
writer = csv.writer(csvout, delimiter=delimiter)
rows = (tuple(item for idx, item in enumerate(row) if idx not in idxs) for row in reader)
writer.writerows(rows)
del_cvs_col('a.csv', 'b.csv', [2])
del_cvs_col 会将 fname 转成 newfname 用 delimiter 来做分割字元,且会去除掉在 idxs中指定的列。