Last active
June 19, 2024 21:54
-
-
Save cgranier/38728d5381b11c694da5c7ff78cf4847 to your computer and use it in GitHub Desktop.
Traverse directories and move all image files (jpg, png, gif) to an "images" directory under the current location
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import shutil | |
def move_images(source_directory, target_directory): | |
# Create the target directory if it doesn't exist | |
if not os.path.exists(target_directory): | |
os.makedirs(target_directory) | |
for root, _, files in os.walk(source_directory): | |
for file in files: | |
if file.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')): | |
source_path = os.path.join(root, file) | |
target_path = os.path.join(target_directory, file) | |
# If a file with the same name already exists in the target directory, | |
# append a number to the file name to make it unique | |
if os.path.exists(target_path): | |
base, extension = os.path.splitext(file) | |
counter = 1 | |
while os.path.exists(target_path): | |
new_file_name = f"{base}_{counter}{extension}" | |
target_path = os.path.join(target_directory, new_file_name) | |
counter += 1 | |
# Move the file | |
shutil.move(source_path, target_path) | |
print(f"Moved: {source_path} to {target_path}") | |
def main(): | |
source_directory = os.getcwd() # Current directory | |
target_directory = os.path.join(source_directory, "images") | |
move_images(source_directory, target_directory) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment