首页 > 解决方案 > 使用加密在python中读写txt

问题描述

我有以下文件 test.txt:

'campo1','campo2','campo3','campo4'    
'2222','34563434','547348568765756556','78967756K      '
'2222','34564232','343575876567567584','65876566W      '
'2222','54754456','234223144675987666','43453534A      '

我需要使用 Crypto.Cipher 库的函数 DES3 加密 campo2、campo3 和 campo4。我写了以下代码:

import pandas as pd
from Crypto.Cipher import DES3
infile = mainpath + "/" + "Prueba Encriptacion.txt"
outfile = mainpath + "/" + "Prueba Encriptacion out.txt"
cipher = DES3.new("4QGdtHLBSKmAJaOJY5BW")
df = pd.read_csv(infile, ',')
for row in df.iterrows():
    campo2_out= cipher.encrypt(campo2)
    campo3_out=cipher.encrypt(campo3)
    campo4_out=cipher.encrypt(campo4)

我的问题是我不知道如何正确遍历文件的行并在 outfile 中写入 cipher.encrypt 函数的结果。

标签: pythonpython-3.xpandas

解决方案


在熊猫中,您通常不会遍历行。您将函数应用于所需的单元格,然后保存生成的数据框。

所以你的代码应该是:

#... read frame as normal...
df["campo2"] = df["campo2"].apply(cipher.encrypt)
df["campo3"] = df["campo3"].apply(cipher.encrypt)
df["campo4"] = df["campo4"].apply(cipher.encrypt)
df.to_csv("outputfile)

推荐阅读