gpt4 book ai didi

python - 如何对 csv 文件中的特定列进行哈希处理?

转载 作者:行者123 更新时间:2023-12-01 08:00:06 26 4
gpt4 key购买 nike

我尝试对第 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

最佳答案

由于您的代码显示您仅尝试对 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 header 写入新文件。

<小时/>

我强烈建议使用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)

关于python - 如何对 csv 文件中的特定列进行哈希处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55775674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com