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

时间:2016-04-28 20:16:33

标签: python csv delete-row

我需要有关代码的指导来编写一个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

1 个答案:

答案 0 :(得分:3)

您需要检查一个id,在设置为整数时转换为整数, 包含在要删除的ID中。 仅在未包含的情况下写入该行。你比较了中的id 第一列,要删除整组ID。一个字符串总是 不等于一套:

if row[0] != Property_ID_To_Delete:

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

变化:

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

成:

infile

修改

在尝试将第一列条目转换为整数之前,您需要首先写入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) 的标题:

var total = 0;
var selectedCount = 0;
var threshold = 6;

$( "#selectable>li.raffle-slot:not('.taken')" ).bind( "click", function ( e ) {
    var price = $(this).data('price');
    if ($(this).hasClass('selected')) {
            total = total - price;
            selectedCount--;
            $(this).toggleClass('selected');
    }
    else if (price + total <= threshold) {
            total = total + price;
            selectedCount++;
            $(this).toggleClass('selected');
    }
    $('#select-result').html(selectedCount);
    $('#price-result').html(total);
});