python编写脚本读取文件夹下的所有数据并从中提取关键字数据

报错1:

UnicodeDecodeError: 'mbcs' codec can't decode byte 0xfc in position 3094: No mapping for the Unicode character exists in the target code page.
# 原因:
# 编码不对

1.需求场景
\capture_info文件夹下有这么多文件,需要所有文本中提取出ip字段
在这里插入图片描述
在这里插入图片描述

2.代码示例

def test_data2():
    # 1.从文件中读取数据
    # 2.从文件中去提取ip
    path = file_path  # 文件夹目录 将路径设置为变量参数
    files = os.listdir(path)  # 得到文件夹下的所有文件名称
    txt_list = []  # 定义空列表来存储

    for file in files:  # 遍历文件夹
        position = path + '\\' + file  # 构造绝对路径,"\\",其中一个'\'为转义符
        print(position)
        with open(position, mode='r', encoding='utf-8') as f:  # 打开文件 #注意编码格式
            date = f.read()  # 读取文件
            txt_list.append(date)  # 添加到数组中
    txt_list = ','.join(txt_list)  # 转化为非数组类型
    # print(type(txt_list))
    # print(txt_list)

    # 提取ip
    ips = re.findall(r"@ijiami_ip:(.+?)@jvm_stack_start", txt_list)
    print(ips)   # 返回一个数组

    # 统计ip出现次数
    ip_num = Counter(ips)
    print(ip_num)

    # 将结果输出到一个txt中
    mylog = open('E:\\mycode\\result_num1.txt', mode='a', encoding='utf-8')
    print(ip_num, file=mylog)
    print(domain_num, file=mylog)
    print('\n')
    mylog.close()
# 运行结果:
Counter({'113.96.232.29:80': 31, '39.103.130.125:443': 2, '110.185.186.35:443': 2, '203.209.230.17:443': 1, '42.120.158.121:80': 1........
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

米雪唲2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值