如果问题很单纯,甚至连 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中指定的列。
温馨提示:答案为网友推荐,仅供参考