如何通过python脚本对csv文件进行排序?

时间:2013-08-23 16:19:35

标签: python sorting csv

我已经在谷歌和本网站上阅读了类似问题的其他答案,但我的脚本中都没有这些答案。

我需要从py脚本的第三列按csv_file对信息进行排序。然后,使用已排序的信息,查找重复项并删除它们,但为csv_file添加计数。

for ip in open("lists.txt"):
    with open("csv_file.csv", "a") as csv_file:
        csv_file.write("\r IP:" + ip.strip() + ", Count, A, B, C \r")
        for line in open("data.txt"):
            new_line = line.split()
            if "word" in new_line:
                if "word"+ip.strip() in new_line:
                    csv_file.write(ip.strip() + ", " + new_line[10].replace("word=", ", ") + new_line[12].replace("word=", ", "))
                    try:
                        csv_file.write(new_line[14].replace("word=", ", "))
                    except IndexError:
                        pass
                    csv_file.write("\r")
with open("csv_file.csv", "r") as inputfile:
    reader = csv.reader(inputfile)
    headers = next(reader)
    for row in reader:
        key = (row[0], row[1:])
        if key not in rows:
            rows[key] = row + [0,]
        rows[key][-1] += 1

我不知道为什么这不起作用,并返回错误,如:

TypeError: unhashable type: 'list'

问题:我如何按第3列排序,删除重复项并通过py脚本向我的csv_file添加重复计数?

1 个答案:

答案 0 :(得分:1)

如果我没弄错,那么“a”标签就会在这一行中开启:

with open("csv_file.csv", "a") as inputfile:

这意味着你要开始写作,而不是阅读。你应该使用“r”或“+”。