I was tasked with creating a script to be able to rename some files and then move them into different folders based on a code in the filename.
import os
import shutil
path = (r"C:\user\reports")
filelist = [ f for f in os.listdir(path) if f.endswith(".xml") ]
for f in filelist:
x = os.path.join(path, f)
os.remove(x)
filelist = [ f for f in os.listdir(path) if f.endswith(".pdf") ]
for f in filelist:
os.rename(os.path.join(path, f),os.path.join(path, f[31:]))
filelist = [f for f in os.listdir(path) if f.endswith(".pdf")]
for f in filelist:
if "A" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderA")
if "B" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderB")
if "C" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderC")
if "D" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderD")
if "E" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderE")
if "F" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderF")
if "G" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderG")
if "H" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderH")
if "I" in f[-6:]: shutil.copy(os.path.join(path, f),r"C:\user\reports\folderI")
filelist = [f for f in os.listdir(path) if f.endswith(".pdf")]
for f in filelist:
x = os.path.join(path, f)
os.remove(x)
First, it removes any XML files in the folder. Then it strips the first 31 characters (it will always be 31 characters) of the filename, leaving just a name and a code. It then checks if the final 6 characters contain a "code" and then move the file to the correct folder based off that code. After every file has been moved, it will delete every file in the parent folder.
I know my current code could be improved, but it's been a couple of years since I've done Python so I've literally done it the easiest way (from what I could Google) possible. Any improvements or suggestions to what features of Python I should be looking at would be great.