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 に答える