使用ZipFile提取含空格路径文件时触发FileNotFoundError求助
解决ZipFile提取时因路径含多余空格触发的FileNotFoundError
问题根源
你猜的没错——报错是因为压缩包内的路径Report/folder1 / subfolder1 / file 1 2022.txt里,folder1 和subfolder1这些目录名带有首尾多余空格。Windows系统不允许目录或文件名的首尾存在空格(系统会自动忽略这类空格,但创建目录时会判定为无效路径),所以extractall尝试创建带空格的目录时就会触发找不到路径的错误。而file2.txt的路径没有多余空格,所以能正常提取。
修复方案
放弃直接使用extractall,改为遍历压缩包内的每个条目,先清理路径中的多余空格,再逐个提取。示例代码如下:
from zipfile import ZipFile import os attachment_filepath = "你的压缩包路径" destination = "Destination" with ZipFile(attachment_filepath, 'r') as z: for entry in z.infolist(): # 拆分原始路径,清理每个路径段的首尾空格 path_segments = entry.filename.split(os.sep) cleaned_segments = [seg.strip() for seg in path_segments if seg.strip()] cleaned_path = os.sep.join(cleaned_segments) # 处理目录:创建清理后的目录(exist_ok=True避免重复创建报错) if entry.is_dir(): os.makedirs(os.path.join(destination, cleaned_path), exist_ok=True) continue # 处理文件:提取到清理后的路径 with z.open(entry) as src_file, open(os.path.join(destination, cleaned_path), 'wb') as dest_file: dest_file.write(src_file.read())
代码解释
- 遍历压缩包内的每个条目(文件/目录),获取原始路径
- 拆分路径为多个段,用
strip()去掉每个段的首尾空格,再重新拼接成合法路径 - 先创建清理后的目录,确保提取文件时父目录存在
- 手动读写文件完成提取,绕开
extractall对含多余空格路径的处理问题
内容的提问来源于stack exchange,提问作者J01
相关产品推荐
相关产品推荐

