Certainly! Let's improve the code by enhancing its readability, robustness, and efficiency. Here's the refactored version with comments explaining the changes:
import json
import os
import shutil
# Path to the JSON file
json_file = 'C:/Users/VovaLT/Desktop/prog/sounds/cleaned_file.json'
# Directory where the files are located
source_directory = os.path.dirname(json_file)
# Directories where files will be moved
matched_directory = os.path.join(source_directory, 'matched_ids')
unmatched_directory = os.path.join(source_directory, 'unmatched_ids')
# Ensure the destination directories exist
os.makedirs(matched_directory, exist_ok=True)
os.makedirs(unmatched_directory, exist_ok=True)
def normalize(value):
"""
Convert value to a lowercase string and strip whitespace.
"""
return str(value).strip().lower()
def extract_ids_from_data(data):
"""
Recursively extract 'id' values from JSON data.
"""
ids = set()
if isinstance(data, dict):
for key, value in data.items():
if key.lower() == 'id':
ids.add(normalize(value))
else:
ids.update(extract_ids_from_data(value))
elif isinstance(data, list):
for item in data:
ids.update(extract_ids_from_data(item))
return ids
def extract_ids(file_path):
"""
Read a JSON file and extract all 'id' values.
"""
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
return extract_ids_from_data(data)
# Extract IDs from the JSON file
ids = extract_ids(json_file)
# Process files in the source directory
for filename in os.listdir(source_directory):
file_path = os.path.join(source_directory, filename)
# Skip directories and JSON files
if os.path.isdir(file_path) or filename.lower().endswith('.json'):
continue
# Extract the base filename without extensions
base_name = filename
while True:
base_name, ext = os.path.splitext(base_name)
if ext == '':
break
# Normalize the base filename
normalized_file_id = normalize(base_name)
# Move the file based on whether its ID matches
if normalized_file_id in ids:
destination = os.path.join(matched_directory, filename)
else:
destination = os.path.join(unmatched_directory, filename)
try:
shutil.move(file_path, destination)
except Exception as e:
print(f"Error moving file {filename}: {e}")
print('Files have been sorted.')
Improvements Made:
-
Modular Functions: The extract_ids_from_data function is now standalone and recursively extracts IDs from the data. This improves readability and reusability.
-
Normalization: A normalize function ensures consistent comparison by converting IDs and filenames to lowercase strings without leading/trailing whitespace.
-
Robust Filename Handling:
- The script now handles files with multiple extensions (e.g.,
.tar.gz) by stripping all extensions to get the base filename.
- This prevents issues where
os.path.splitext might not handle multiple extensions correctly.
-
Error Handling: Added a try-except block around shutil.move to catch and report any file-moving errors without stopping the script.
-
Skipping Directories and JSON Files:
- The script now skips over any directories found in the source directory.
- It also skips all JSON files, not just the main JSON file, ensuring they aren't accidentally moved.
-
Comments and Readability: Added comments throughout the code for better understanding and maintenance.
-
Avoiding Hardcoded Paths: While the original path is kept for context, using os.path.join and os.path.dirname makes the code platform-independent and avoids issues with slashes.
Additional Suggestions:
-
Logging: For a production environment, consider using the logging module instead of print statements to provide configurable log levels and outputs.
-
Configuration: Externalize paths and configurations to a separate file or command-line arguments to make the script more flexible.
-
Testing: Add unit tests to verify that extract_ids_from_data and other functions behave correctly with various JSON structures.
By implementing these changes, the script becomes more robust, maintainable, and adaptable to different scenarios.