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'?
CodePudding user response:
There are a few errors:
you did not import urllib, which is the reson for the error message that you got: ->
from urllib import parse
you want to encode, not decode: ->
base64.b64encode
you're also missing the
import csv
row
is not defined: -> changer
torow
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')