使用加密在python中读写txt

时间:2019-03-18 10:48:06

标签: python python-3.x pandas

我有以下文件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)

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

3 个答案:

答案 0 :(得分:1)

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

因此您的代码应为:

#... 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)

答案 1 :(得分:0)

我不得不对您的代码进行一些修改才能使其重现。但是一旦成功,我就可以使用applymap,就像这样:

from Crypto.Cipher import DES3
from Crypto.Random import get_random_bytes

key = DES3.adjust_key_parity(get_random_bytes(24))
cipher = DES3.new(key, DES3.MODE_CFB)

df = pd.read_csv('test.txt', ',')
df = df.astype(str)
df = df.applymap(lambda x: cipher.encrypt(x.encode('UTF-8')))

给你

campo1               campo2                                 campo3                                              campo4
0   b'\xe1#[\xd3'           b'\xe2\x9ee\xb4\xf1\xc4o\xa4'   b'w\xc0:\\Cn\xc7\x9f\xc4A\x93\x1e\x8c\xde\xa0\...   b'm>\xc2\xb3\xe3\xeb\xe6\\('
1   b'\x95\xea\xac\xed'     b'\xa6;\xfd\xb2\x98e\xd0\x8d'   b'01sVHg2j\xd0\x8f\xee\x90\x1a&\xd0\xae\xeb\xb3'    b'\xdb\x06\xcdh\x01\xce\xfdv\xca'
2   b'[\xfd\xf5A'           b'|\x85W\xe4\x19\x83(X'         b'\xb9E+\x00\xcf\\\xa2\r,\xa6\x9a\xf9\x0b[g\xe...   b'\xa4\xd2\x14&\x8c:\xf8N\xdc'

答案 2 :(得分:0)

您可以使用python csv.reader使用csv.writer读取csv

代码如下:

import csv
from Crypto.Cipher import DES3

cipher = DES3.new("4QGdtHLBSKmAJaOJY5BW")
infile = mainpath + "/" + "Prueba Encriptacion.txt"
outfile = mainpath + "/" + "Prueba Encriptacion out.txt"


def encrypt_csv(file_name):
    with open(file_name, 'r') as csv_file:
        with open(outfile, 'w') as out_file:
            reader = csv.reader(csv_file, delimiter=",")
            writer = csv.writer(out_file, delimiter=",")
            for row in reader:
                encrypted_data = [cipher.encrypt(data) for data in row]
                writer.writerow(encrypted_data)


if __name__ == '__main__':
    encrypt_csv(infile)