[英]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.我正在尝试对第 2 列和第 8 列进行哈希处理,但最终对整个文件进行了哈希处理。 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.由于您的代码显示您仅尝试对
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')
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).您的代码的问题在于这一行
newfile.write(hashing + '\n')
,因为这只将散列密码写入文件(没有其他列)。 Also you didn't write the CSV header to the new file.此外,您没有将 CSV 标头写入新文件。
I strongly suggest using Pandas
:我强烈建议使用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.