摘要
shell 中无法正常访问带空格或某些字符的目录,写了个脚本规范一下中文路径命名
将指定目录下所有子目录和文件命名中的、,。()!、?:“”‘’【】《》()
全部替换为_
,去除首尾的_
。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import os import re
def normalize_chinese_path(directory): for root, dirs, files in os.walk(directory): for dirname in dirs: new_dirname = re.sub(r'[\s、,。()!、?:“”‘’【】《》()]+', '_', dirname) new_dirname = new_dirname.strip('_') if new_dirname != dirname: old_path = os.path.join(root, dirname) new_path = os.path.join(root, new_dirname) os.rename(old_path, new_path)
for filename in files: new_filename = re.sub(r'[\s、,。()!?:“”‘’【】《》()]+', '_', filename) new_filename, suffix = os.path.splitext(new_filename) new_filename = new_filename.strip('_') if new_filename != filename: old_path = os.path.join(root, filename) new_path = os.path.join(root, new_filename + suffix) os.rename(old_path, new_path)
normalize_chinese_path('./03 golang微服务实战/')
|