tutorial_9.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. def new_file_sort():
  2. if not os.path.exists('analytics'):
  3. os.mkdir('analytics')
  4. new = []
  5. head = []
  6. with open('studentinfo_cs384.csv', newline='') as csvfile:
  7. reader = csv.DictReader(csvfile)
  8. for row in reader:
  9. head = list(row.keys())
  10. del head[1]
  11. head.insert(1,'first_name')
  12. head.insert(2,'last_name')
  13. k = list(row.values())
  14. del k[1]
  15. k.insert(1,row['full_name'].split()[0])
  16. k.insert(2,' '.join(row['full_name'].split()[1:]))
  17. new.append(k)
  18. csvfile.close()
  19. with open('analytics/studentinfo_cs384_names_split.csv', newline='',mode='w') as f:
  20. f_write = csv.writer(f, delimiter=',',lineterminator='\r')
  21. f_write.writerow(head)
  22. for i in new:
  23. f_write.writerow(i)
  24. f.close()
  25. #sorting
  26. dic = {}
  27. for i in new:
  28. dic[i[1]]='#$%^&*'.join(i)
  29. new = []
  30. with open('analytics/studentinfo_cs384_names_split_sorted_first_name.csv', mode = 'w') as f:
  31. print
  32. f.close()
  33. for i in sorted(dic.items()):
  34. new.append(i[1].split('#$%^&*'))
  35. with open('analytics/studentinfo_cs384_names_split_sorted_first_name.csv', mode = 'a') as f:
  36. f_write = csv.writer(f, delimiter=',',lineterminator='\r')
  37. f_write.writerow(head)
  38. for i in new:
  39. f_write.writerow(i)
  40. f.close()