Saturday, 5 October 2019

Unable to shift values under one header to another

I'm trying to swap values between two cells under the headers Title and Name in a csv file based on a condition. I get success when the headers are like:

Organization Working since Gender Title Name ID

However, when they are like the following (multiple headers having the same set of names) I get stuck:

Organization Working since Gender Title Name ID Title Name ID

What I'm trying to do is check whether the header Title contains any value but Name doesn't. If that is true then the content under the header Title will be shifted to Name. However, if the content under the header Name has already any value then leave them as they are.

I've tried with (works when there is a single set of header):

import csv

with open('profile_info.csv', 'r') as infile, open('modified.csv', 'w', newline="") as outfile:
    reader = csv.DictReader(infile)
    writer = csv.DictWriter(outfile, fieldnames=['Title','Name','ID'])
    writer.writeheader()
    for row in reader:
        if not row['Name']:
            row['Name'] = row['Title']

            """I don't know any better option for the following line"""

            row['Title']= ""
        else:
            row['Title'],row['Name']
        writer.writerow(row)
        print(row['Title'],row['Name'])

Image of profile_info.csv file.

Image of modified.csv file.

If you wanna test yourself, this is the main csv file for your convenience.



from Unable to shift values under one header to another

No comments:

Post a Comment