Advertisement
homeworkhelp111

Write

Feb 6th, 2022 (edited)
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. # Import the CSV module
  2. import csv
  3.  
  4. def main():
  5. # Create an empty dictionary
  6. dct ={}
  7.  
  8. # Read the rows from oldCSV.csv
  9. with open('oldCSV.csv') as f:
  10. # Read all the lines
  11. lines = f.readlines()
  12.  
  13. # count to skip the headers
  14. count = 0
  15.  
  16. # For each row read from the file
  17. for line in lines:
  18. if(count == 0): #To skip headers
  19. count += 1
  20. else:
  21. # We split the column by using split and comma as delimiter
  22. # Each column will be stored in the words list
  23. words = line.split(',')
  24.  
  25. # Make sure that the columns read are more than 1
  26. if(len(words)> 1):
  27. dct[words[0]] = [words[1],words[2], words[3].strip()]
  28.  
  29. # Similarly we read from newCSV file
  30. with open('newCSV.csv') as f:
  31. lines = f.readlines()
  32. count = 0
  33. for line in lines:
  34. if(count == 0): #To skip headers
  35. count += 1
  36. else:
  37. words = line.split(',')
  38. if(len(words)> 1):
  39. # This will overwrite any keys in the dictionary read from OldCSV
  40. # At the same time it will add new rows from newCSV
  41. dct[words[0]] = [words[1],words[2], words[3].strip()]
  42.  
  43. # Headers for writing to oldCSV.csv file
  44. fields = ['id','Phone Number','Credit Number','Level Complete']
  45.  
  46. # writing to csv file
  47. with open("OldCSV.csv", 'w',newline='') as csvfile:
  48. # creating a csv writer object
  49. csvwriter = csv.writer(csvfile)
  50.  
  51. # writing the header fields
  52. csvwriter.writerow(fields)
  53.  
  54. # Sort the keys (i.e. IDs) and for each key we write the values to oldCSV.csv
  55. for key in sorted(dct.keys()):
  56. # Combine the key + values of that key to write to the CSV file
  57. # e.g. if '1': ['123','456','789']
  58. # we will write ['1','123','456','789']
  59. lst = [key]+dct[key]
  60.  
  61. # Write the above combined list
  62. csvwriter.writerow(lst)
  63.  
  64. if __name__=='__main__':
  65. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement