Java&Python批量修改文件名,帮助忙于修改文件名的各位

修改文件名

每次面对一大堆的文件要修改文件名的时候都会和头疼,明明都要求好了,却还是有人不按照规则命名。
所以!!!

import os
import re
p_Url = '文件夹的路径'
realColumn = '班级+姓名+学号'
#班级学号等等各种命名方式,用‘+’链接,一定要用‘+’(其他规则的没有写)
delimiter = '-'#指定分割符,如:会计-张三-333333-第一次作业(注意这里用的是‘-’,链接,如果将‘-’改为‘+’,那么就会用‘+’链接)
'''
查看谁没交
'''
id_list = []
name_list = []
stMap = {}
RL = []
idLong = 0
AllPeople = 0
'''
查看谁没交
'''
def getFileName():
    sl = os.listdir(p_Url)
    student_Id = []
    copystMap = stMap.copy()
    for s in sl:
        student_Id.append(mathId(s))
    for x in student_Id:
        if x not in id_list:
            print('重复人员')
            exit(-1)
        id_list.remove(x)
    s_l = []
    for i in id_list:
        s_l.append(stMap.get(i))
    print('共  {}  人,已交  {}  人,未交  {}  人\n没交人员:{}'.format(AllPeople,AllPeople-len(s_l),len(s_l),s_l))
    pass
def mathId(s):
    reString = '[0-9]{'+str(idLong)+',}'
    result =  re.findall(reString, s)
    if len(result) == 0:
        return matchName(s)
    return result[0]

def matchName(name):
    for x in stMap.keys():
        name_ = stMap.get(x)
        if name_ in name:
            return x

def getMap():
    global AllPeople
    #文件名为Student.txt放在该文件同目录
    with open('Student.txt', 'r', encoding='utf8') as f:
        ss = f.readlines()
    for s in ss:
        r = s.split(' ')
        name = r[1].strip()
        name_list.append(name)
        id = r[0]
        stMap[id] = name
        id_list.append(id)
        global idLong
        idLong = len(id)
        AllPeople +=1

def getName():
    sl = os.listdir(p_Url)
    str = ''
    reString = '[0-9]{' + str(idLong) + ',}'
    for x in sl:
        id = re.findall(reString , x)[0]
        str = str+id+' '
        name = x.split('+')[1]
        str = str+name+'\n'
    with open('Student.txt', 'w', encoding='utf8') as f:
        f.write(str)

def reName():
    sl = os.listdir(p_Url)
    for x in sl:
        id = mathId(x)
        name = stMap.get(id)
        s = ''
        for r in RL:
            if r=='id':
                s = s+str(id)
            elif r=='name':
                s = s+str(name)
            else:
                s = s+r
            s = s+delimiter
        s = s[0:-1]
        suffix = x.split('.')[-1]
        url = p_Url+'//'+x
        new_name = p_Url+'//'+s+"."+suffix
        os.rename(url,new_name)

def getMathFileName():
    rs = realColumn.split('+')
    for r in rs:
        if r in id_list:
            RL.append('id')
        elif r in name_list:
            RL.append('name')
        else:
            RL.append(r)

if __name__ == '__main__':
    getMap()
    getMathFileName()
    getFileName()
    reName()

Studens.txt中的文件
学号/编号 姓名
如:
54334343434 张三
43526262625 李四

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @program: Demo
 * @Auther: 月色真美
 * @Date: 2021/10/20/21:29
 * @Description: 
 */
public class Main {
    static HashMap<String,String> NI = null;
    static HashMap<String,String> IN = null;
    static String NameIdFile = "";
    static List<String> Names = new ArrayList<>();
    static List<String> Ids = new ArrayList<>();
    static String matchString ="";
    static String delimiter = "+";
    static {
        NI = new HashMap<>();
        IN = new HashMap<>();
        try {
            NameIdFile = new File(Main.class.getResource("").toURI().getPath()).toString()+"\\Student.txt";
            loadNameIdMap();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String url = "文件路径";
        getFileNames(url);
        getWho(url);
        mathString("班级+姓名+第五章作业");
        //班级学号等等各种命名方式,用‘+’链接
        reName(url);
    }

    public static File[] getFileNames(String url){
        final File file = new File(url);
        return  file.listFiles();
    }

    public static void getWho(String url){
        final File[] fileNames = getFileNames(url);
        for (File x : fileNames){
            String id = matchId(x.getName());
            Ids.remove(id);
        }
        final StringBuffer stringBuffer = new StringBuffer("");
        stringBuffer.append("未交人员有:\t");
        for (String x:Ids){
            stringBuffer.append(IN.get(x)+"\t");
        }
        System.out.println(stringBuffer);
    }

    public static String matchId(String s){
        final Pattern compile = Pattern.compile("[0-9]{12,}");
        final Matcher matcher = compile.matcher(s);
        if (matcher.find()){
            return matcher.group(0);
        }else {
            return matchName(s);
        }
    }

    private static String matchName(String s) {
        for (String name:Names){
            if (s.contains(name)){
                return NI.get(name);
            }
        }
        return null;
    }

    public static void loadNameIdMap() throws IOException {
        File file = new File(NameIdFile);
        final FileReader fileReader = new FileReader(file);
        final BufferedReader bufferedReader = new BufferedReader(fileReader);
        String s = null;
        while ((s = bufferedReader.readLine()) != null){
            final String[] s1 = s.split(" ");
            String name = s1[1];
            Names.add(name);
            String id = s1[0];
            Ids.add(id);
            IN.put(id,name);
            NI.put(name,id);
        }
    }

    public static void reName(String url){
        final List<String> list = mathString("大数据1903+徐明强 541912290323");
        final File file = new File(url);
        final File[] files = file.listFiles();
        final ArrayList<String> strings = new ArrayList<>();
        for (File f:files){
            String fileName = f.getName();
            String suffix = fileName.split("\\.")[1];
            final String id = matchId(fileName);
            StringBuffer newFileName = new StringBuffer();
            for (String l:list){
                if (l.equals("name")){
                    newFileName.append(IN.get(id));
                    newFileName.append(delimiter);
                }else if (l.equals("id")){
                    newFileName.append(id);
                    newFileName.append(delimiter);
                }else {
                    newFileName.append(l);
                    newFileName.append(delimiter);
                }
            }
            String string = newFileName.substring(0,newFileName.length()-2);
            string = string+"."+suffix;
            String newFilePath = f.getParent()+"\\"+string;
            f.renameTo(new File(newFilePath));
        }
    }

    public static List<String> mathString(String s){
        final String[] split = s.split("\\+|\\-| ");
        final ArrayList<String> strings = new ArrayList<>();
        for (String x:split){
            if (NI.get(x) != null){
                strings.add("name");
            }else if(IN.get(x) != null){
                strings.add("id");
            }else {
                strings.add(x);
            }
        }
        return strings;
    }
}

最后,补充一点Students.txt的文件是必须的,因为必须要有人员与编号之间的对应关系。
如果其中有错误,请大家指正。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值