You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python3 zipfile模块创建压缩包时遇文件找不到错误的解决问询

Fixing FileNotFoundError When Creating ZIP with Python's zipfile Module

Hey there! That FileNotFoundError you're hitting makes total sense—let's break it down and fix it without changing your working directory.

The Root Cause

Your script uses os.listdir(path) which returns just the raw filenames (like file.xml) instead of full absolute paths. When you pass that short filename to z.write(i), Python looks for the file in your current working directory (where your script lives, /Users/xxxx/scripts) instead of the target reports directory you specified.


Solution 1: Use Full File Paths

The simplest fix is to combine your base path with each filename to create a complete, absolute path to the XML file. I also swapped your manual z.close() with a with statement—this is a Python best practice because it automatically closes the zip file even if an error pops up:

import datetime
import os
import zipfile

path = '/Users/xxxx/reports/xxxx/monthly'
month = datetime.datetime.now().strftime('%G-%B')
zf = os.path.join(path, '{}.zip'.format(month))

with zipfile.ZipFile(zf, 'w') as z:
    for filename in os.listdir(path):
        if filename.endswith('.xml'):
            full_file_path = os.path.join(path, filename)
            z.write(full_file_path)

Solution 2: Keep Zip Archive Filenames Clean

If you don't want the full system path showing up inside the zip file (you just want file.xml instead of /Users/xxxx/reports/xxxx/monthly/file.xml), use the arcname parameter. This lets you define what name the file will have inside the archive:

import datetime
import os
import zipfile

path = '/Users/xxxx/reports/xxxx/monthly'
month = datetime.datetime.now().strftime('%G-%B')
zf = os.path.join(path, '{}.zip'.format(month))

with zipfile.ZipFile(zf, 'w') as z:
    for filename in os.listdir(path):
        if filename.endswith('.xml'):
            full_file_path = os.path.join(path, filename)
            z.write(full_file_path, arcname=filename)

This way, your zip will contain only the XML filenames, keeping the archive neat and organized.


内容的提问来源于stack exchange,提问作者Marct

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:22:23