2013-08-23 67 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」或「+」。

相關問題