Python实现通过目录路径识别.tar.gz文件并提取其中JPG/PNG图片(适配Tkinter GUI图像分类项目)
Problem Statement
I'm working on an image classification project's Tkinter GUI module, and I need to extract all .jpg and .png images from .tar.gz archives in a specific folder. The catch is I can't use a filename-specific extraction method—instead, I need to identify the .tar.gz extension to process the files. My current code doesn't throw errors but fails to run properly.
My Attempted Code
import os import tarfile def extractfile(): os.chdir('GUI_Tkinter/PMC_downloads') with tarfile.open(os.path.join(os.environ['GUI_Tkinter/PMC_downloads'], f'Backup_{self.batch_id}.tar.gz'), "r:gz") as so: so.extractall(path=os.environ['GUI_Tkinter/PMC_downloads'])
Solution
Let's fix this step by step. First, let's address the issues in your original code:
os.environ['GUI_Tkinter/PMC_downloads']is incorrect:os.environaccesses environment variables, not file system paths.extractall()extracts everything in the archive, but you only need image files.- Using
os.chdir()can cause unexpected behavior in your GUI if other components rely on the current working directory.
Here's a robust, targeted solution that meets your requirements:
Targeted Image Extraction (Single Specific Tar File)
This version processes your Backup_{self.batch_id}.tar.gz file and extracts only JPG/PNG images:
import os import tarfile def extract_images_from_tar(self): # Safely build paths (works across Windows/macOS/Linux) target_folder = os.path.join(os.getcwd(), 'GUI_Tkinter', 'PMC_downloads') output_folder = target_folder # Use a different path here if you want images in a separate folder # Path to your specific tar.gz file tar_file_path = os.path.join(target_folder, f'Backup_{self.batch_id}.tar.gz') # Check if the tar file exists first if not os.path.exists(tar_file_path): print(f"Error: Archive {tar_file_path} not found.") return try: with tarfile.open(tar_file_path, "r:gz") as tar: # Loop through all files in the archive for member in tar.getmembers(): # Extract only JPG/PNG (case-insensitive to handle .JPG/.Png) if member.name.lower().endswith(('.jpg', '.jpeg', '.png')): tar.extract(member, path=output_folder) print(f"Extracted image: {member.name}") print("Image extraction completed successfully!") except tarfile.TarError as e: print(f"Failed to process tar archive: {e}") except Exception as e: print(f"Unexpected error: {e}")
Process All .tar.gz Files in the Folder
If you need to extract images from all .tar.gz archives in the target folder (not just one specific file), use this variation:
import os import tarfile def extract_images_from_all_tars(self): target_folder = os.path.join(os.getcwd(), 'GUI_Tkinter', 'PMC_downloads') output_folder = target_folder # Loop through all files in the folder for filename in os.listdir(target_folder): # Only process .tar.gz files if filename.endswith('.tar.gz'): tar_file_path = os.path.join(target_folder, filename) try: with tarfile.open(tar_file_path, "r:gz") as tar: for member in tar.getmembers(): if member.name.lower().endswith(('.jpg', '.jpeg', '.png')): tar.extract(member, path=output_folder) print(f"Extracted from {filename}: {member.name}") print(f"Completed processing {filename}") except tarfile.TarError as e: print(f"Error with {filename}: {e}") except Exception as e: print(f"Unexpected error with {filename}: {e}")
Key Notes for Tkinter Integration
- Make sure
self.batch_idis properly populated (e.g., from a text input field or dropdown in your GUI). - Bind this function to a button's
commandparameter like so:Button(root, text="Extract Images", command=self.extract_images_from_tar).pack() - Add status messages to your GUI (instead of
print()) using aLabelorTextwidget to keep users informed.
内容的提问来源于stack exchange,提问作者Sachin Sinkar

