我們如何在給定的父文件夾中替換文件夾,子文件夾和文件名稱中的空格?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('*')
什麼是目標 - 結果或程序本身? – TigerhawkT3
你可以在這裏使用os.walk()這樣的答案:http://stackoverflow.com/questions/16953842/using-os-walk-to-recursively-traverse-directories-in-python – minhhn2910