[英]How to recursively loop through a file structure and rename directories in python
I would like to resursively rename directories by changing the last character to lowercase (if it is a letter) 我想通过将最后一个字符更改为小写(如果它是一个字母)来重复重命名目录
I have done this with the help of my previous posts (sorry for the double posting and not acknowledging the answers) 我在以前的帖子的帮助下完成了这个(抱歉双重发布而不是确认答案)
This code works for Files, but how can I adapt it for directories as well? 此代码适用于文件,但我如何适应目录呢?
import fnmatch
import os
def listFiles(dir):
rootdir = dir
for root, subFolders, files in os.walk(rootdir):
for file in files:
yield os.path.join(root,file)
return
for f in listFiles(r"N:\Sonstiges\geoserver\IM_Topo\GIS\MAPTILEIMAGES_0\tiles_2"):
if f[-5].isalpha():
os.rename(f,f[:-5]+f[-5].lower() + ".JPG")
print "Renamed " + "---to---" + f[:-5]+f[-5].lower() + ".JPG"
The problem is that the default of os.walk is topdown. 问题是os.walk的默认值是topdown。 If you try to rename directories while traversing topdown, the results are unpredictable.
如果您尝试在遍历topdown时重命名目录,则结果是不可预测的。
Try setting os.walk
to go bottom up: 尝试将
os.walk
设置为自下而上:
for root, subFolders, files in os.walk(rootdir,topdown=False):
Edit 编辑
Another problem you have is listFiles()
is returning, well, files not directories. 你遇到的另一个问题是
listFiles()
返回,好吧,文件不是目录。
This (untested) sub returns directories from bottom up: 这个(未经测试的)子从下到上返回目录:
def listDirs(dir):
for root, subFolders, files in os.walk(dir, topdown=False):
for folder in subFolders:
yield os.path.join(root,folder)
return
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.