Windows 用 zip 压缩文件夹时报错:
'<文件>' cannot be compressed because includes characters that cannot be used in a compressed folder, such as <非法字符>. You should rename this file or directory.
同 [1]。考虑用 python 批量检测非 ascii 字符,并重命名。参考 [2] 检测非 ascii 字符。
- 只改了文件名,没改目录名,可按需自加
import os, os.path as osp
def clean(s):
"""清除文件名不合法字符"""
s = ' '.join(s.split())
s = s.replace('\n', '')
s = s.replace('\t', '')
s = s.replace('\r', '')
s = ''.join([_s for _s in s if _s.isascii()])
return s
P = r"C:\Users\itom\paper"
for root, dirs, files in os.walk(P):
for f in files:
if not f.isascii(): # 含非 ascii 字符
new_f = clean(f)
assert new_f.isascii(), f
os.rename(osp.join(root, f), osp.join(root, new_f))