zoukankan      html  css  js  c++  java
  • 删除目录中文件名的尾巴

    可以很方便的扩展为目录中修改文件的内容

    1.修改前

    2.修改后

    import os
    import sys
    
    
    # 文件重命名
    def rename_file(old_file, new_file):
        os.rename(old_file, new_file)
        print('%s -------> %s completed.' % (old_file, new_file))
    
    
    
    # 遍历一个目录
    def trav_dir(dir, str_del):
        file_list = os.listdir(dir)
        for file in file_list:
            # 获取文件完整路径
            file_path = os.path.join(dir, file)
            if os.path.isdir(file_path):
                trav_dir(file_path, str_del)
            else:
                # 文件名替换
                if str_del in file:
                    new_file = file.replace(str_del, '')
                    # 对文件改名
                    new_file_path = os.path.join(dir, new_file)
                    # 对文件重命名
                    rename_file(file_path, new_file_path)
    
    
    if __name__ == '__main__':
        # 获取目录
        if len(sys.argv) >= 3:
            wk_dir = sys.argv[1]
            str_del = sys.argv[2]
        else:
            print('输入不正确![格式:目录名 删除的字符]')
            exit(-1)
    
        # 遍历一个目录
        trav_dir(wk_dir, str_del)
  • 相关阅读:
    近似计算π(for循环)
    apache部署mo_python
    文件注释方法
    算法效率的度量
    ssh
    使用类名创建对象
    筛选网址
    常用django命令
    查看和关闭端口
    update脚本出错
  • 原文地址:https://www.cnblogs.com/linxmouse/p/9850678.html
Copyright © 2011-2022 走看看