① 目的
- 电脑使用时间长,保存了极多的WORD与EXCEL文件
- 文件版本不同(.doc .docx .xls .xlsx …)
- 文件内保存有重要的身份信息(身份证号、手机号…)
- 要求对word和excel文件进行加密操作
② 代码(Version: 3.8.1)
1. 遍历所有文档
import psutil
import xlrd
import os
import itertools
import re
import time
import win32com.client
from typing import Generator, Any
from itertools import product
def fp_generator():
# 先获取电脑所有磁盘名称,导出利用os.walk()导出所有文件路径
for disk in [device[0] for device in psutil.disk_partitions()][::-1]: # 获得电脑所有磁盘名称
for root, dirs, files in os.walk(disk):
for file in files:
yield os.path.join(root, file)
2. 获取Word与Excel文件的内容
(结果多次试验,若频繁地Quit掉win32.client.Dispathch(“Word.Application”),再立刻创建并访问word文件,会报错,原因可能是windows系统还未真正关闭上一个对象,造成句柄冲突。因此一定要time.sleep,至少0.1秒。
但是Excel完全没有这个问题,这是让人头大的windows api)
def excel_values(path) -> Generator[str, Any, Any]:
# 获得所有EXCEL单元格(文本&数字)内容。若捕获错误,则为已加密文件打开时报错;或文件已损坏
try:
with xlrd.open_workbook(path) as wb:
for sheet in wb.sheets():
for x, y in itertools.product(range(sheet.ncols), range(sheet.nrows)):
cell = sheet.cell(y, x)
if cell.ctype == 1:
yield cell.value
elif cell