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)









你可能感兴趣的:(Python文本处理脚本,python,正则表达式)