Python中.zip文件解压函数失效问题排查求助
ZIP文件解压函数extractall()报错问题排查与解决
我编写了一个unzip_file函数,预期功能是接收一个ZIP文件路径,将其解压到原文件所在目录,代码如下:
def unzip_file(file_path): print(f"Unzipping file: {file_path}") if os.path.exists(file_path): if file_path[-4:] == ".zip": with zipfile.ZipFile(file_path, 'r') as zip_ref: try: for file_name in zip_ref.namelist(): print(f"Found in zip: {file_name}") print(os.path.dirname(file_path)) zip_ref.extractall(path=os.path.dirname(file_path)) except Exception as e: print(f"Error unzipping file: {e}") os.remove(file_path) else: print(f"File is not a zip file: {file_path}") else: print(f"File does not exist: {file_path}")
测试场景:ZIP文件名为zip_file.zip,路径为C:\example_folder\zip_file.zip,内部包含三个无文件夹的文本文件a.txt、b.txt、c.txt。运行时出现错误,报错信息如下:
Unzipping file: C:\example_folder\zip_file.zip Found in zip: a.txt Found in zip: b.txt Found in zip: c.txt C:\example_folder Error unzipping file: [Errno 2]: No such file or directory- 'C:\\example_folder\\zip_file.zip\\a.txt'
请问extractall()为何无法正常工作?
问题解决
已排查出问题根源:文件路径过长。特此告知有类似问题的用户,确保文件路径长度不超过256字符即可解决该问题。
内容的提问来源于stack exchange,提问作者MSuccessor
相关产品推荐
相关产品推荐

