濟(jì)南網(wǎng)站建設(shè)找大標(biāo)深圳網(wǎng)站seo地址
通常為了防止重要的Excel文件數(shù)據(jù)內(nèi)容的泄露,需要對文件整體進(jìn)行加密與解密的操作。
對于文件的加解密過程,python也有很多非標(biāo)準(zhǔn)庫來幫助我們完成操作,這里主要說明如何完成對Excel文件的解密與讀取操作。
這里我們使用到的是msoffcrypto-tool非標(biāo)準(zhǔn)庫,可以選擇使用pip的方式安裝一下即可。
pip intall msoffcrypto-tool
該msoffcrypto-tool模塊提供了代碼層面的解密操作,也提供了CLI終端命令直接解密的操作。
1.使用終端命令
通過在終端命令行輸入下面的命令即可完成對Office文件解密操作。
msoffcrypto-tool '加密文件路徑' '解密文件路徑' -p 123456
其中利用-p參數(shù)設(shè)置123456為解密文件需要的密碼,可以使用該密碼來完成解密操作。
2.使用python API
將示例中需要的解密的python模塊都導(dǎo)入到當(dāng)前的代碼塊中。
# Importing the pandas module and renaming it as pd.
import pandas as pd# Importing the msoffcrypto module and renaming it as pto.
import msoffcrypto as pto
開始進(jìn)行解密操作之前,我們首先將加密后的excel原始文件讀取為File文件對象。
# Opening the file in binary mode.
file_ = pto.OfficeFile(open('D:/test/data.xlsx', 'rb'))
其次,對File文件對象設(shè)置文件解密時需要的密碼,使用load_key函數(shù)加載密碼。
# Loading the password into the file object.
file_.load_key(password='123456')
然后,同樣使用File文件對象的decrypt函數(shù)可以完成對Excel文件的解密操作。
# Decrypting the file and saving it to the path specified.
file_.decrypt(open('./data_decrypted.xlsx', 'wb'))
至此,文件解密過程已經(jīng)完成了,接下來只需要對生成的沒有密碼的新文件進(jìn)行操作就可以了。
這里我們使用常用的pandas模塊完成了對數(shù)據(jù)的讀取操作就OK了。
# Reading the excel file and storing it in a dataframe.
data_frame = pd.read_excel('./data_decrypted.xlsx')# Printing the dataframe.
print(data_frame)
關(guān)于更多的詳細(xì)內(nèi)容可以參考github上面作者對于msoffcrypto相關(guān)的詳細(xì)說明。
https://github.com/nolze/msoffcrypto-tool
往期精彩
python最好用的能源類可視化圖表模塊,沒有之一!
如何解決python讀取大數(shù)據(jù)量文件時造成的內(nèi)存溢出?
python情感分析:基于jieba的分詞及snownlp的情感分析!