【发布时间】:2017-05-01 18:50:04
【问题描述】:
我们如何替换给定父文件夹中文件夹、子文件夹和文件名称中的空格?
下面给出了我最初尝试替换到 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('*')
【问题讨论】:
-
目标是什么——结果,还是程序本身?
-
您可以在此处的答案中使用 os.walk() :stackoverflow.com/questions/16953842/…
标签: python batch-rename