linux下中文路径命名规范化

摘要

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微服务实战/')
- ETX   Thank you for reading -
  • Copyright: All posts on this blog except otherwise stated, All adopt CC BY-NC-ND 4.0 license agreement. Please indicate the source of reprint!