Skip to content

linux下中文路径命名规范化

摘要

shell 中无法正常访问带空格或某些字符的目录,写了个脚本规范一下中文路径命名

将指定目录下所有子目录和文件命名中的、,。()!、?:“”‘’【】《》()全部替换为_,去除首尾的_。

代码

python
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微服务实战/')