您应该使用该
csv模块读取制表符分隔的值文件。不要 不
读入内存中一气呵成。毕竟,您阅读的每一行都有将行写入输出CSV文件所需的所有信息。始终保持打开输出文件。
import csvwith open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout: tsvin = csv.reader(tsvin, delimiter='t') csvout = csv.writer(csvout) for row in tsvin: count = int(row[4]) if count > 0: csvout.writerows([row[2:4] for _ in range(count)])
或者,使用
itertools模块重复以下 *** 作
itertools.repeat():
from itertools import repeatimport csvwith open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout: tsvin = csv.reader(tsvin, delimiter='t') csvout = csv.writer(csvout) for row in tsvin: count = int(row[4]) if count > 0: csvout.writerows(repeat(row[2:4], count))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)