简体   繁体   中英

How do I hash specific columns from a csv file?

I'm trying to hash column 2 and 8 but I ended up hashing the entire file. What's the issue with my code?

import csv
import hashlib


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

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

        reader = csv.DictReader(csvfile)

        for r in reader:

            hashing = hashlib.sha256((r['Password']).encode('utf-8')).hexdigest()

            newfile.write(hashing + '\n')

在此处输入图像描述

在此处输入图像描述

Since your code showing your attempt to hash the Password column only, the following code just does the hashing for the Password column.

import csv
import hashlib

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

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

        reader = csv.DictReader(csvfile)

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

            # hashing the 'Password' column
            r['Password'] = hashlib.sha256((r['Password']).encode('utf-8')).hexdigest()

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

The issue with your code is with this line newfile.write(hashing + '\n') , as this writes only the hashed password to the file (without the other columns). Also you didn't write the CSV header to the new file.


I strongly suggest using Pandas :

import pandas as pd
import hashlib

# reading CSV input
df = pd.read_csv('UserInfo.csv')

# hashing the 'Password' column
df['Password'] = df['Password'].apply(lambda x: \
        hashlib.sha256(x.encode('utf-8')).hexdigest())

# writing the new CSV output
df.to_csv('UserInfo_Hashed.csv', index=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM