Search code examples
pythoncsvbase64export-to-csv

Encode a column in CSV to Base64


I'll preface by saying I'm a novice with Python, but I'm trying to encode a single column from a CSV to Base64 and write to another CSV. The file has 3 columns (consumer_id, sms_number, email_address) and I only want to encode the 'consumer_id'. Here is what I have as of now:

import base64

with open('File1.csv') as csvfile:

    with open('File2.csv', 'w') as newfile:

        reader = csv.DictReader(csvfile)

        for i, r in enumerate(reader):
            #  writing csv headers
            if i == 0:
                newfile.write(','.join(r) + '\n')

            # convert 'ID' column to Base64
            r['consumer_id'] = base64.b64decode(parse.unquote(row['consumer_id']))

            # writing the new row to the file
            newfile.write(','.join(r.values()) + '\n')

The error I get is

Traceback (most recent call last):
  File "c:\script.py", line 93, in <module>
    r['consumer_id'] = base64.b64decode(parse.unquote(row['consumer_id']))
NameError: name 'parse' is not defined. Did you mean: 'vars'?

Solution

  • There are a few errors:

    1. you did not import urllib, which is the reson for the error message that you got: -> from urllib import parse

    2. you want to encode, not decode: -> base64.b64encode

    3. you're also missing the import csv

    4. row is not defined: -> change r to row

    Full code:

    import base64
    import csv
    from urllib import parse
    
    with open('C:/temp/File1.csv') as csvfile:
    
        with open('C:/temp/File2.csv', 'w') as newfile:
    
            reader = csv.DictReader(csvfile)
    
            for i, row in enumerate(reader):
                #  writing csv headers
                if i == 0:
                    newfile.write(','.join(row) + '\n')
    
                # convert 'ID' column to Base64
                row['consumer_id'] = base64.b64encode(parse.unquote(row['consumer_id']).encode()).decode()
    
                # writing the new row to the file
                newfile.write(','.join(row.values()) + '\n')