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 osimport shutilpath = (rC:\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),rC:\user\reports\folderA)    if B in f[-6:]: shutil.copy(os.path.join(path, f),rC:\user\reports\folderB)    if C in f[-6:]: shutil.copy(os.path.join(path, f),rC:\user\reports\folderC)    if D in f[-6:]: shutil.copy(os.path.join(path, f),rC:\user\reports\folderD)    if E in f[-6:]: shutil.copy(os.path.join(path, f),rC:\user\reports\folderE)    if F in f[-6:]: shutil.copy(os.path.join(path, f),rC:\user\reports\folderF)    if G in f[-6:]: shutil.copy(os.path.join(path, f),rC:\user\reports\folderG)    if H in f[-6:]: shutil.copy(os.path.join(path, f),rC:\user\reports\folderH)    if I in f[-6:]: shutil.copy(os.path.join(path, f),rC:\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.
Manipulating filenames using Python
python;strings;python 2.7;file
Don't reinvent the wheelFor getting the files with a specific extension you should use glob:xmlFiles = glob.glob('*.xml')(Note that this will work relative to the current path.)Avoid code duplicationYou have some serious code duplication going on, replace it my appropriate code like:#I don't really know the semantics of your paths so you should rename this accordinglyallowedPaths = 'ABCDEFGHI'for filename in filelist:        for character in allowedPaths:        if character in f[-6:]: shutil.copy(os.path.join(path, f),                                             os.join.path(path, rfolder + character))Magic numbersAvoid these magic numbers by replacing them with constantsPREFIX_LENGTH = 31POSTFIX_LENGTH = 6#...os.rename(os.path.join(path, f),os.path.join(path, f[PREFIX_LENGTH:]))#...if character in f[-POSTFIX_LENGTH:]: