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

yipeiwu_com6年前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相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python常用遍历技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python语言实现机器学习的K-近邻算法

Python语言实现机器学习的K-近邻算法

写在前面 额、、、最近开始学习机器学习嘛,网上找到一本关于机器学习的书籍,名字叫做《机器学习实战》。很巧的是,这本书里的算法是用Python语言实现的,刚好之前我学过一些Python基础...

python列表生成式与列表生成器的使用

列表生成式:会将所有的结果全部计算出来,把结果存放到内存中,如果列表中数据比较多,就会占用过多的内存空间,可能会导致MemoryError内存错误或者导致程序在运行时出现卡顿的情况 列表...

python 中文字符串的处理实现代码

>>> teststr = '我的eclipse不能正确的解码gbk码!' >>> teststr '\xe6\x88\x91\xe7\x9a\x84...

以windows service方式运行Python程序的方法

本文实例讲述了以windows service方式运行Python程序的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python # coding...

python实现每次处理一个字符的三种方法

本文实例讲述了python每次处理一个字符的三种方法。分享给大家供大家参考。 具体方法如下: a_string = "abccdea" print 'the first' f...