Python遍历目录更换文件名和目录名

简介:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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)


相关阅读:

1、Python文件(夹)基本操作

2、os.scandir()


*** walker ***

本文转自walker snapshot博客51CTO博客,原文链接http://blog.51cto.com/walkerqt/1369880如需转载请自行联系原作者


RQSLT

相关文章
|
1天前
|
Python
【Python进阶(五)】——模块搜索及工作目录
【Python进阶(五)】——模块搜索及工作目录
|
1天前
|
存储 Linux Shell
python移除/删除非空文件夹/目录的最有效方法是什么?
python移除/删除非空文件夹/目录的最有效方法是什么?
11 0
|
1天前
|
机器学习/深度学习 存储 数据挖掘
Python中遍历并修改列表的综合指南
Python中遍历并修改列表的综合指南
17 2
|
1天前
|
存储 数据挖掘 Python
Python技术分享:实现选择文件或目录路径的方法
Python技术分享:实现选择文件或目录路径的方法
19 2
|
1天前
|
Linux Python Windows
Python更换国内pip源详细教程
Python更换国内pip源详细教程
|
1天前
|
JSON JavaScript 数据格式
python遍历目录文件_结合vue获取所有的html文件并且展示
python遍历目录文件_结合vue获取所有的html文件并且展示
10 0
|
1天前
|
Python
Python 合并多个 PDF 文件并建立书签目录
Python 合并多个 PDF 文件并建立书签目录
16 1
|
1天前
|
数据安全/隐私保护 Python
Python文件与目录操作:面试中的高频考点
【4月更文挑战第15天】本文介绍了Python文件和目录操作的面试重点,包括文件的读写、目录遍历及权限管理。强调了文件关闭、异常处理、特殊文件判断以及权限位和权限字符串的理解。提供了代码示例,如读写文件、遍历目录和更改文件权限,帮助读者在面试中表现出色。掌握这些技能将对编程求职之路大有裨益。
18 0
|
1天前
|
索引 容器
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
|
1天前
|
索引 Python
在Python中,如何快速地遍历列表中的每个元素?
在Python中,如何快速地遍历列表中的每个元素?
35 3