2013-08-23 40 views
0

我已经阅读了谷歌和本网站上类似问题的其他答案,并没有一个在我的脚本中工作。如何通过python脚本对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?

+0

您的意思是'reader.next()',而不是'next(reader)' – yosukesabai

+0

csv文件有多大? – wflynny

+0

@yosukesabai:为什么'reader.next()'? @bill:266KB – hjames

回答

1

如果我没有记错的“一”的标签打开了在这一行写着:

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

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

相关问题