源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python遍历目录并批量更换文件名和目录名的方法

  • 时间:2022-11-14 19:17 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python遍历目录并批量更换文件名和目录名的方法
本文实例讲述了Python遍历目录并批量更换文件名和目录名的方法。分享给大家供大家参考,具体如下:
#encoding=utf-8
#author: walker
#date: 2014-03-07
#summary: 深度遍历指定目录,并将子目录和文件名改为小写
#注意,此程序只针对windows,windows下文件(夹)名不区分大小写
import os
import os.path
import shutil
#读入指定目录并转换为绝对路径
rootdir = raw_input('root dir:\n')
rootdir = os.path.abspath(rootdir)
print('absolute root path:\n*** ' + rootdir + ' ***')
#先修改文件名
for parent, dirnames, filenames in os.walk(rootdir):
  for filename in filenames:
    pathfile = os.path.join(parent, filename)
    pathfileLower = os.path.join(parent, filename.lower())
    if pathfile == pathfileLower:  #如果文件名本身就是全小写
      continue
    print(pathfile + ' --> ' + pathfileLower)
    os.rename(pathfile, pathfileLower)
#后修改目录名,这里注意topdown参数。
#topdown决定遍历的顺序,如果topdown为True,则先列举top下的目录,然后是目录的目录,依次类推;
#反之,则先递归列举出最深层的子目录,然后是其兄弟目录,然后父目录。
#我们需要先修改深层的子目录
for parent, dirnames, filenames in os.walk(rootdir, topdown=False):
  for dirname in dirnames:
    pathdir = os.path.join(parent, dirname)
    pathdirLower = os.path.join(parent, dirname.lower())
    if pathdir == pathdirLower: #如果文件夹名本身就是全小写
      continue
    print(pathdir + ' --> ' + pathdirLower)
    os.rename(pathdir, pathdirLower)

更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/672.htm]Python文本文件操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/699.htm]Python常用遍历技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/645.htm]Python图片操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/648.htm]Python Socket编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》及《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部