作业讲解

import xlrd
import os
# pip install msoffcrypto-tool 解除文件保护
# -i https://pypi.tuna.tsinghua.edu.cn/simple/
import msoffcrypto


filepath = "D:/4"
key_string = "华新现代大数据技术与应用"
os.listdir(filepath)


# 文件解除保护
#def jc_xls():
    # file = msoffcrypto.OfficeFile(open('encrypted.xls', 'rb'))  # 读取原文件
    # file.load_key(password='VelvetSweatshop')  # 填入设置保护时设置的密码, 默认密码为 'VelvetSweatshop'
    # file.decrypt(open('decrypted.xls', 'wb'))  # 解密后保存为新文件, 新文件无保护,可直接使用 xlrd 读取内容

# xls文件的查询
def select_xls(file_path, key_str):
    try:
        sheet = xlrd.open_workbook(file_path)
        sheets = sheet.sheets()
        # 循环遍历所有的sheet
        for i in range(1, len(sheets)):
            table = sheet.sheet_by_index(i)
            nRows = table.nrows
            # 嵌套循环读取行
            for j in range(0, nRows):
                rowData = table.row_values(j)
                if key_str in rowData:
                    print("找到关键词在:" + file_path + "内")
    except Exception as e:
        # import traceback
        # traceback.print_exc()
        return



# 递归的方式找到文件
def select_file_path(file_path):
    for name in os.listdir(file_path):
        new_path = file_path + "/" + name
        # 判断这个路径是否表示文件夹
        if os.path.isdir(new_path):
            select_file_path(new_path)
        # 如果不是文件夹,即是有后缀的那些文件
        else:
            # 分离文件名与扩展名,返回元组(f_name, f_extension)
            ext = os.path.splitext(name)[1]
            if ext == ".xls":
                select_xls(new_path, "华新现代大数据技术与应用")


# 调用方法
select_file_path(filepath)

 

最后修改于 2021-03-22 15:04:33
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇