我们如何在给定的父文件夹中替换文件夹,子文件夹和文件名称中的空格?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