The project outline:
Write a program that walks through a folder tree and searches for files with a certain file extension (such as .pdf or .jpg). Copy these files from whatever location they are in to a new folder.
My solution:
import os, shutil
from pathlib import Path
def copy_extension(basedir, newdir, extension):
for foldername, subfolders, filenames in os.walk(basedir):
for filename in filenames:
if not filename.endswith(extension):
continue
file_path = Path(foldername) / Path(filename)
destination = newdir / filename
if destination.exists():
new_destination = copy_increment(destination)
shutil.copy(file_path, new_destination)
else:
shutil.copy(file_path, destination)
def copy_increment(destination):
marker = 0
stem, extension = os.path.splitext(destination)
while destination.exists():
marker += 1
destination = Path(f"{stem} ({marker}){extension}")
return destination
def main():
while True:
user_search = input("Please enter a folder to search: ")
basedir = Path(user_search)
if not basedir.is_dir():
print("This path does not exist.")
continue
else:
user_destination = input("Please enter a the director of the new folder: ")
newdir = Path(user_destination)
extension = input("Extension of files to copy: ")
copy_extension(basedir, newdir, extension)
if __name__ == '__main__':
main()
firemore, as it is simpler. Butclickallows for more customisation \$\endgroup\$