peaceandiago peaceandiago - 4 months ago 5x
Python Question

Appending back to the file/dictionary after hashing (and anonymizing names)

so I have a question as to how to move forward. I have a csv file that goes like
[Name ,Date/Time,Message,Major,Minor,Tone,Crisis,Suicide,Poster,Topics Tags]

I just need to anonymize the Names and I used hash in order to do that. I was able to isolate the Names and hash them but I don't really know how to append it back and create a new csv file with the new anonymized names (but with the original data) I currently have:

import hashlib

with open("example.csv") as f:
for ex in f:
list = ex.split(",")
name = list[0]
# prints the isolated names
hashObject = hashlib.md5(name.encode())
print hashObject.hexdigest()


Following code should work, it will replace the first item on every row with hashed value and write the result to new file:

import hashlib

with open('example.csv') as fin, open('output.csv', 'w') as fout:
    for ex in fin:
        items = ex.split(',')
        items[0] = hashlib.md5(items[0].encode()).hexdigest()