Python根据文本内容对文件进行分类

# !/usr/bin/evn python
# -*- coding:utf-8 -*-
import os
import shutil
import re
import codecs

src_dir_path = r'C:\Users\Administrator\PycharmProjects\源文件'        # 源文件夹
   
first_filer = r'C:\Users\Administrator\PycharmProjects\存放分类文件的文件夹\first_filer '# 存放分类文件的文件夹
#第一类文件存放的位置
second_filer = r''
#第二类文件存放的位置

if os.path.exists(src_dir_path):
    for file in os.listdir(src_dir_path):
        if os.path.isfile(src_dir_path+'/'+file):
            f = open(src_dir_path+"\\"+file,'r',encoding='utf-8').read()
            #打开文件
            if re.search("某一字符串", f):
            #判断文件内容
                print('找到包含"' + '某一字符串' + '"字符的文件,绝对路径为----->' + src_dir_path + '/' + file)
                # print('移动到----->'+first_filer +file)
                if not os.path.exists(first_filer ):
                #判断是否存在文件夹,不存在则创建
                    os.mkdir(first_filer , 1)
                    os.rename(src_dir_path + '\\' + file, first_filer + '\\' + file)
                else:
                    os.rename(src_dir_path + '\\' + file, first_filer + '\\' + file)
            if re.search('某一字符串2',f):
                print('找到包含"' + '某一字符串2' + '"字符的文件,绝对路径为----->' + src_dir_path + '/' + file)
                # print('移动到----->'+second_filer  +file)
                if not os.path.exists(second_filer ):
                    os.mkdir(second_filer , 1)
                    os.rename(src_dir_path + '\\' + file, second_filer + '\\' + file)
                else:
                    os.rename(src_dir_path + '\\' + file, second_filer  + '\\' + file)









  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值