2016-12-16 128 views
4

我們如何在給定的父文件夾中替換文件夾,子文件夾和文件名稱中的空格?Python:如何用所有文件,文件夾和子文件夾的名稱中的下劃線替換空格?

我最初嘗試替換到第8級,如下所示。我相信有更好的方法。我的代碼看起來很難看。 更好的解決方案是值得歡迎的。

#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 
# 


def replace_space_by_underscore(path): 
    """Replace whitespace in filenames by underscore.""" 
    import glob 
    import os 
    for infile in glob.glob(path): 
     new = infile.replace(" ", "_") 
     try: 
      new = new.replace(",", "_") 
     except: 
      pass 
     try: 
      new = new.replace("&", "_and_") 
     except: 
      pass 
     try: 
      new = new.replace("-", "_") 
     except: 
      pass 
     if infile != new: 
      print(infile, "==> ", new) 
     os.rename(infile, new) 

if __name__ == "__main__": 
    try: 
     replace_space_by_underscore('*/*/*/*/*/*/*/*') 
    except: 
     pass 
    try: 
     replace_space_by_underscore('*/*/*/*/*/*/*') 
    except: 
     pass 
    try: 
     replace_space_by_underscore('*/*/*/*/*/*') 
    except: 
     pass 
    try: 
     replace_space_by_underscore('*/*/*/*/*') 
    except: 
     pass 
    try: 
     replace_space_by_underscore('*/*/*/*') 
    except: 
     pass 
    try: 
     replace_space_by_underscore('*/*/*') 
    except: 
     pass 
    try: 
     replace_space_by_underscore('*/*') 
    except: 
     replace_space_by_underscore('*') 
+0

什麼是目標 - 結果或程序本身? – TigerhawkT3

+1

你可以在這裏使用os.walk()這樣的答案:http://stackoverflow.com/questions/16953842/using-os-walk-to-recursively-traverse-directories-in-python – minhhn2910

回答

6

你可以使用os.walk,使您可以即時修改的迭代文件夾的名稱:

import os 

def replace(parent): 
    for path, folders, files in os.walk(parent): 
     for f in files: 
      os.rename(os.path.join(path, f), os.path.join(path, f.replace(' ', '_'))) 
     for i in range(len(folders)): 
      new_name = folders[i].replace(' ', '_') 
      os.rename(os.path.join(path, folders[i]), os.path.join(path, new_name)) 
      folders[i] = new_name 

os.walk遍歷目錄樹從parent在自上而下的順序開始。對於每個文件夾,它返回元組(current path, list of files, list of folders)。鑑於文件夾列表可以被突變,並且os.walk將在迭代的以下步驟中使用突變的內容。運行前

文件夾:

. 
├── new doc 
└── sub folder 
    ├── another folder 
    ├── norename 
    └── space here 

後:

. 
├── new_doc 
└── sub_folder 
    ├── another_folder 
    ├── norename 
    └── space_here 
+0

能夠使用' os.rename'作爲重命名文件的方法幫助了我,謝謝 –

1

您需要遞歸解決方案。重命名當前目錄中的所有文件;然後對於每個子目錄(如果有的話),進入子目錄X(使用os.chdir(X)),再次調用相同的函數,然後返回父目錄(使用os.chdir(".."))。

1

繼我結束了這個@niemmi的確切想法:

警告:不要運行該腳本HOME目錄或從一些重要的目錄中,它會重命名包括HIDDEN文件的所有文件。

#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 
# Date: Dec 15, 2016 


def replace_space_by_underscore(parent): 
    """Replace whitespace by underscore in all files and folders. 

    replaces , - [ ]() __ ==> underscore 

    """ 
    import os 
    for path, folders, files in os.walk(parent): 
     # rename the files 
     for f in files: 
      old = os.path.join(path, f) 
      bad_chars = [r' ', r',', r'-', r'&', r'[', r']', r'(', r')', r'__'] 
      for bad_char in bad_chars: 
       if bad_char in f: 
        new = old.replace(bad_char, '_') 
        print(old, "==>", new) 
        os.rename(old, new) 

     # rename the folders 
     for i in range(len(folders)): 
      new_name = folders[i].replace(' ', '_') 
      bad_chars = [r' ', r',', r'-', r'&', 
         r'[', r']', r'(', r')', r'__'] 
      for bad_char in bad_chars: 
       if bad_char in new_name: 
        new_name = new_name.replace(bad_char, '_') 
        print(folders[i], "==> ", new_name) 
      old = os.path.join(path, folders[i]) 
      new = os.path.join(path, new_name) 
      os.rename(old, new) 
      folders[i] = new_name 


if __name__ == "__main__": 
    replace_space_by_underscore('.') 
相關問題