3

大写字母 - 它们有什么意义?他们给你的只是rsi。

我想从我的目录结构中删除尽可能多的大写字母。我将如何在 python 中编写脚本来执行此操作?

它应该递归地解析指定的目录,用大写字母标识文件/文件夹名称,并将它们重命名为小写。

4

2 回答 2

16

os.walk非常适合对文件系统进行递归处理。

import os

def lowercase_rename( dir ):
    # renames all subforders of dir, not including dir itself
    def rename_all( root, items):
        for name in items:
            try:
                os.rename( os.path.join(root, name), 
                                    os.path.join(root, name.lower()))
            except OSError:
                pass # can't rename it, so what

    # starts from the bottom so paths further up remain valid after renaming
    for root, dirs, files in os.walk( dir, topdown=False ):
        rename_all( root, dirs )
        rename_all( root, files)

向上遍历树的意义在于,当您拥有像“/A/B”这样的目录结构时,您在递归期间也将拥有路径“/A”。现在,如果您从顶部开始,您首先将 /A 重命名为 /a,从而使 /A/B 路径无效。另一方面,当您从底部开始并首先将 /A/B 重命名为 /A/b 时,它不会影响任何其他路径。

实际上你也可以使用os.walk自上而下,但这(稍微)更复杂。

于 2010-06-19T13:33:29.547 回答
2

尝试以下脚本:

#!/usr/bin/python

'''
renames files or folders, changing all uppercase characters to lowercase.
directories will be parsed recursively.

usage: ./changecase.py file|directory
'''

import sys, os

def rename_recursive(srcpath):
    srcpath = os.path.normpath(srcpath)
    if os.path.isdir(srcpath):
        # lower the case of this directory
        newpath = name_to_lowercase(srcpath)
        # recurse to the contents
        for entry in os.listdir(newpath): #FIXME newpath
            nextpath = os.path.join(newpath, entry)
            rename_recursive(nextpath)
    elif os.path.isfile(srcpath): # base case
        name_to_lowercase(srcpath)
    else: # error
        print "bad arg: " + srcpath
        sys.exit()

def name_to_lowercase(srcpath):
    srcdir, srcname = os.path.split(srcpath)
    newname = srcname.lower()
    if newname == srcname:
        return srcpath
    newpath = os.path.join(srcdir, newname)
    print "rename " + srcpath + " to " + newpath
    os.rename(srcpath, newpath)
    return newpath

arg = sys.argv[1]
arg = os.path.expanduser(arg)
rename_recursive(arg)
于 2010-06-19T12:22:09.803 回答