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)
    
  • 相关阅读:
    matplotlib
    Scipy-数值计算库
    Django Templates
    Django Views: Dynamic Content
    Django Views and URLconfs
    Opencv读写文件
    Logistic回归
    demo
    【Python62--scrapy爬虫框架】
    【Python58--正则2】
  • 原文地址:https://www.cnblogs.com/jie9527-/p/11811914.html
Copyright © 2011-2022 走看看