merge_lines.py 1020 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import csv
  2. ## open CSV file and rea it
  3. myfile = open('text.csv', "r")
  4. reader = csv.reader(myfile, delimiter=";")
  5. ## create an empty dictionary
  6. mydictionary = {}
  7. rownum = 0
  8. for row in reader:
  9. ## check if it is the header
  10. if rownum == 0:
  11. pass
  12. else:
  13. ## split the line of CSV in elements..Use the name for the key in dictionary and the other two in a list
  14. #line = row.split(";")
  15. #print(row)
  16. text = row[0]
  17. #print(text)
  18. x = row[1]
  19. y = row[2]
  20. if x in mydictionary:
  21. mydictionary[text][1] += text
  22. print(mydictionary[text][1] )
  23. else:
  24. mydictionary[text] = [x,y]
  25. rownum += 1
  26. myfile.close()
  27. ## create a new list of lists with the data from the dictionary
  28. newcsvfile = ["text","x","y"]
  29. for i in mydictionary:
  30. newcsvfile.append(mydictionary[i])
  31. ## write the new list of lists in a new CSV file
  32. with open("output.csv", "wb") as f:
  33. writer = csv.writer(f)
  34. writer.writerows(newcsvfile)