Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Import the CSV module
- import csv
- def main():
- # Create an empty dictionary
- dct ={}
- # Read the rows from oldCSV.csv
- with open('oldCSV.csv') as f:
- # Read all the lines
- lines = f.readlines()
- # count to skip the headers
- count = 0
- # For each row read from the file
- for line in lines:
- if(count == 0): #To skip headers
- count += 1
- else:
- # We split the column by using split and comma as delimiter
- # Each column will be stored in the words list
- words = line.split(',')
- # Make sure that the columns read are more than 1
- if(len(words)> 1):
- dct[words[0]] = [words[1],words[2], words[3].strip()]
- # Similarly we read from newCSV file
- with open('newCSV.csv') as f:
- lines = f.readlines()
- count = 0
- for line in lines:
- if(count == 0): #To skip headers
- count += 1
- else:
- words = line.split(',')
- if(len(words)> 1):
- # This will overwrite any keys in the dictionary read from OldCSV
- # At the same time it will add new rows from newCSV
- dct[words[0]] = [words[1],words[2], words[3].strip()]
- # Headers for writing to oldCSV.csv file
- fields = ['id','Phone Number','Credit Number','Level Complete']
- # writing to csv file
- with open("OldCSV.csv", 'w',newline='') as csvfile:
- # creating a csv writer object
- csvwriter = csv.writer(csvfile)
- # writing the header fields
- csvwriter.writerow(fields)
- # Sort the keys (i.e. IDs) and for each key we write the values to oldCSV.csv
- for key in sorted(dct.keys()):
- # Combine the key + values of that key to write to the CSV file
- # e.g. if '1': ['123','456','789']
- # we will write ['1','123','456','789']
- lst = [key]+dct[key]
- # Write the above combined list
- csvwriter.writerow(lst)
- if __name__=='__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement