2010-06-19 37 views
3

大寫字母 - 他們有什麼意義?他們給你的只是rsi。(python)遞歸從目錄結構中刪除大寫?

我想從我的目錄結構中刪除儘可能多的資本化成爲可能。我將如何編寫一個腳本來做到這一點在Python中?

應該遞歸解析指定的目錄,用大寫字母標識的文件/文件夾的名稱和小寫的重新命名。

回答

12

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自上而下過,但是這(略)更復雜。

+1

該腳本還應該重命名文件。另外,在mid-walk中更改目錄結構是否會混淆os.walk功能? – 2010-06-20 05:53:44

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) 
+0

使用'os.walk'來簡化你的第一個功能:http://docs.python.org/library/os.html#os.walk – 2010-06-19 13:36:05

+0

不爲東西壞的解決方案不使用'os.walk'! :) – jathanism 2010-09-10 17:21:00