使用Python3 zipfile模块创建压缩包时遇文件找不到错误的解决问询
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

