zoukankan      html  css  js  c++  java
  • 批量修改文件名字或后缀

    修改任意目录下文件名字

    import os
    path_dir = r'目录地址'
    # 获取目录下的所有文件
    a = os.listdir(path_dir)
    n = 0
    for i in a:
        n += 1
        x = str(n)
        # 分割路径,返回路径名和文件扩展名的元组
        ext = os.path.splitext(i)
        # 只修改后缀为.txt的文件
        if ext[1] == '.txt':
            # 修改后的名字
            new_name = x + ext[1]
            # 要修改的路径下的文件
            oldfile = os.path.join(path_dir, i)
            # 修改后名字的路径
            newfile = os.path.join(path_dir, new_name)
            # 重命名
            os.rename(oldfile, newfile)
    

    修改当前目录下文件名字

    import os
    # 当前目录
    path_dir = os.getcwd()
    # 获取目录下的所有文件
    a = os.listdir()
    n = 0
    for i in a:
        n += 1
        x = str(n)
        # 分割路径,返回路径名和文件扩展名的元组
        ext = os.path.splitext(i)
        # 只修改后缀为.txt的文件
        if ext[1] == '.txt':
            # 修改后的名字
            new_name = x + ext[1]
            # 要修改的路径下的文件
            oldfile = os.path.join(path_dir, i)
            # 修改后名字的路径
            newfile = os.path.join(path_dir, new_name)
            # 重命名
            os.rename(oldfile, newfile)
    

    修改当前目录下文件后缀

    import os
    # 当前目录
    path_dir = os.getcwd()
    # 获取目录下的所有文件
    a = os.listdir()
    for i in a:
        # 分割路径,返回路径名和文件扩展名的元组
        ext = os.path.splitext(i)
        # 想要修改的为什么
        if ext[1] == '':
            # 修改后的名字
            new_name = ext[0] + ''
            # 要修改的路径下的文件
            oldfile = os.path.join(path_dir, i)
            # 修改后名字的路径
            newfile = os.path.join(path_dir, new_name)
            # 重命名
            os.rename(oldfile, newfile)
    
  • 相关阅读:
    决策树简介
    机器学习一百天-day7/11-KNN
    机器学习100天-day4,5,6,8逻辑回归
    机器学习一百天-day3多元线性回归及虚拟变量陷阱分析
    机器学习100天-day2简单线性回归
    机器学习100天-day1数据预处理
    sklearn.preprocessing.Imputer
    vue echart 中国地图 疫情图
    一周笔记
    js基础操作与方法
  • 原文地址:https://www.cnblogs.com/jie9527-/p/11811914.html
Copyright © 2011-2022 走看看