python自动化操作_文件和目录的批量重命名操作

  • Post author:
  • Post category:python


一、文件和文件夹的批量重命名

1.文件重命名使用os库里的rename函数。os.rename(old,new)

二、复杂路径中的文件重命名

1.注意文件夹修改的时候,会只修改最外层的文件夹,因为改了后就变了名字,找不到啦。解决办法:加topdown=False,由内到外。

import os,random
path1="E:\研究生"
for paths, dirnames, filenames in os.walk(path1,topdown=False):
    print("当前路径:",paths)
    print("当前路径包含的文件夹:",dirnames)
    print("当前路径包含的文件名:",filenames)  
    print("\n") 
    for filename in filenames:
        filename_path=os.path.join(paths,filename)
        new_filename="研究生_"+filename
        new_filename_path=os.path.join(paths,new_filename)
        os.rename(filename_path,new_filename_path)
        print(filename_path,"改成",new_filename_path)
    for dirname in dirnames:
        dirname_path=os.path.join(paths,dirname)
        new_dirname=str(random.randint(100,999))
        new_dirname_path=os.path.join(paths,new_dirname)
        os.rename(dirname_path,new_dirname_path)
        print(dirname_path,"改成",new_dirname_path)



版权声明:本文为weixin_67677814原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。