This is my solution to the Chapter 9 exercise in Automate the Boring Stuff:
Write a program that walks through a folder tree and searches for files with a certain file extension (such as
.jpg). Copy these files from whatever location they are in to a new folder.
#!/usr/local/bin/python3 #selectiveCopy.py - Walks through a folder tree with the extension .PDF and copies them to a new folder. import re import os import shutil filePdf = re.compile(r"""^(.*?) #text before extension [.][p][d][f] #extension .pdf """, re.VERBOSE) def selectiveCopy(fileExtension): for pdfFiles in os.listdir("/Users//Desktop/newPDFs"): locatedFiles = filePdf.search(pdfFiles) if locatedFiles != None: print(locatedFiles) files_to_copy = os.path.join("/Users/my_user_name/Desktop/newPDFs", pdfFiles) ` shutil.copy(files_to_copy, "/Users/my_user_name/Desktop/oldPDFs") print("The following file has been copied " + files_to_copy) selectiveCopy(filePdf)
I appreciate for probably all of you on here that it's not a very difficult exercise, but I've been working through this book slowly and have just decided it's probably a good idea to start putting them on a Github page. I wanted to know if I could improve the code to make it more efficient or if there are some things I've included that aren't necessarily considered "standard practice".