创建从旧 CSV 中排除行的新 CSV

Create new CSV that excludes rows from old CSV

我需要代码指导来编写一个 CSV 文件,该文件在第一列 [0] 中删除具有特定数字的行。我的脚本写入一个文件,但它包含我正在努力删除的行。我怀疑电子表格被读取为一个长字符串而不是 ~150 行可能有问题。

import csv

Property_ID_To_Delete = {4472738, 4905985, 4905998, 4678278, 4919702, 4472936, 2874431, 4949190, 4949189, 4472759, 4905977, 4905995, 4472934, 4905982, 4906002, 4472933, 4905985, 4472779, 4472767, 4472927, 4472782, 4472768, 4472750, 4472769, 4472752, 4472748, 4472751, 4905989, 4472929, 4472930, 4472753, 4933246, 4472754, 4472772, 4472739, 4472761, 4472778}

with open('2015v1.csv', 'rt') as infile:
    with open('2015v1_edit.csv', 'wt') as outfile:
        writer = csv.writer(outfile)
        for row in csv.reader(infile):
            if row[0] != Property_ID_To_Delete:
                writer.writerow(row)

数据如下: https://docs.google.com/spreadsheets/d/19zEMRcir_Impfw3CuexDhj8PBcKPDP46URZ9OA3uV9w/edit?usp=sharing

您需要检查一个id,是否像您设置的那样转换为整数, 包含在要删除的 ID 中。 仅当不包含该行时才写入该行。你比较中的id 包含要删除的整组 ID 的第一列。一个字符串总是 不等于集合:

>>> '1' != {1}
True

因此,您将获得输出中的所有行。

变化:

if row[0] != Property_ID_To_Delete:

进入:

if int(row[0]) not in Property_ID_To_Delete:

编辑

在尝试将第一列条目转换为整数之前,您需要先写入 infile 的 header:

with open('2015v1.csv', 'rt') as infile:
    with open('2015v1_edit.csv', 'wt') as outfile:
        writer = csv.writer(outfile)
        reader = csv.reader(infile)
        writer.writerow(next(reader))
        for row in reader:
            if int(row[0]) not in Property_ID_To_Delete:
                writer.writerow(row)