我正在尝试编写python(2.7)脚本,以将多个CSV列表添加在一起(简单追加),但不添加文件X中与文件Y共享元素(第一栏中除外)的任何行。这是我的试用脚本:
import csv
import glob
with open('merged.csv','wb') as out:
seen = set()
output = []
out_writer = csv.writer(out)
csv_files = glob.glob('*.csv')
for filename in csv_files:
with open(filename, 'rb') as ifile:
read = csv.reader(ifile)
for row in read:
if {row[1] not in seen} & {row[2] not in seen} & {row[3] not in seen}:
seen.add(row[1])
seen.add(row[2])
seen.add(row[3])
output.append(row)
out_writer.writerows(output)
我敢肯定,这可以清除一些,但这是试运行-为什么它不正确地将第2、3和4列中的元素添加到所看到的集合中,如果它们出现在所考虑的行中,则不追加该行?除了正确检查重复项以外,它还可以成功输出合并的文件。(如果合并的文件已经存在于目录中,这也将起作用,否则我会遇到麻烦吗?)
提前非常感谢!:)
我怀疑这条线不能满足您的要求:
if {row[1] not in seen} & {row[2] not in seen} & {row[3] not in seen}:
那是一个设定的交集。演示:
>>> {False} & {True}
set([])
>>> {True} & {True}
set([True])
>>> {False} & {False}
set([False])
>>> bool(set([False]))
True #non-empty set is True in boolean context
也许你打算
if row[1] not in seen and row[2] not in seen and row[3] not in seen:
或(几乎*)等价物
if all(value not in seen for value in row[1:4]):
(*)如果行中的值较少,则不会引发异常
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句