如何从csv文件中哈希特定列?

问题描述 投票:1回答:1

我正在尝试哈希第2列和第8列,但我最终散列整个文件。我的代码有什么问题?

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')

enter image description here

enter image description here

python csv hash
1个回答
1
投票

由于您的代码仅显示您尝试散列Password列,因此以下代码仅对Password列进行散列处理。

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')

你的代码的问题在于这行newfile.write(hashing + '\n'),因为它只将散列密码写入文件(没有其他列)。您也没有将CSV标头写入新文件。


我强烈建议使用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)
© www.soinside.com 2019 - 2024. All rights reserved.