python3文件加密_将加密的csv导入Python 3

为了在Jupyter notebook上进行数据协作分析,博主计划将敏感的CSV数据存储在GitHub仓库中。为保护数据,他选择了在运行时通过密码提示解密的方式,利用Python 3.6和SimpleCrypt库加密文件。加密过程涉及读取CSV文件、使用用户密码加密内容并保存为'file.enc',解密时通过getpass获取密码,解密内容并用pandas加载到DataFrame中。
摘要由CSDN通过智能技术生成

So I am planning to do some data analysis using a Jupyter notbook (Python 3), for collaborative reasons I want to store the data on a github repo, however the data set is sensitive.

As such I would like to store the data (currently .csv) as an encrypted file on the repo and then decrypt it at runtime (with a password prompt I guess).

What is the best method to do this?

解决方案

In the end, I used python 3.6 and SimpleCrypt to encrypt the file and then uploaded it.

I think this is the code I used to encrypt the file:

f = open('file.csv','r').read()

ciphertext = encrypt('USERPASSWORD',f.encode('utf8'))#this .encode('utf8') is the bit im unsure about

e = open('file.enc','wb') # file.enc doesn't need to exist, python will create it

e.write(ciphertext)

e.close

This is the code I use to decrypt at runtime, I run getpass("password: ") as an argument so I don't have to store a password variable in memory

from io import StringIO

import pandas as pd

from simplecrypt import encrypt, decrypt

from getpass import getpass

# opens the file

f = open('file.enc','rb').read()

print('Please enter the password and press the enter key \n Decryption may take some time')

# Decrypts the data, requires a user-input password

CSVplaintext = decrypt(getpass("password: "), f).decode('utf8')

print('Data have been Decrypted')

#create a temp csv-like file to pass to pandas.read_csv()

DATA=StringIO(CSVplaintext)

# Makes a panda dataframe with the data

df = pd.read_csv(DATA)

Note, the UTF-8 encoding behaviour is different in python 2.7 so the code will be slightly different.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值