(Python)ディレクトリ構造から大文字を再帰的に削除しますか?

StackOverflow https://stackoverflow.com/questions/3075443

  •  28-09-2019
  •  | 
  •  

質問

大文字 - それらのポイントは何ですか?彼らがあなたに与えるのはRSIだけです。

ディレクトリ構造からできるだけ多くの大文字を削除したいと思います。 Pythonでこれを行うためにスクリプトを書くにはどうすればよいですか?

指定されたディレクトリを再帰的に解析し、ファイル/フォルダー名を大文字で識別し、小文字で名前を変更する必要があります。

役に立ちましたか?

解決

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に名前を変更した場合、他のパスには影響しません。

実際に使用できます os.walk トップダウンの場合も、それは(わずかに)より複雑です。

他のヒント

次のスクリプトを試してください。

#!/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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top