borfo
borfo

Reputation: 213

Python: add dic values to filename

I was trying to create sub-folders based on parts of the filenames. I have the following examples of files in the directory:

xxx.01.741425.xlsx

xxx.12.658521.xlsx

xxx.01.667423.xlsx

xxx.12.125867.xls

xxx.12.355456.xlsx

I wanted all the files with 01 after xxx. in one subfolder named 01, all the files with 12 after xxx. in another subfolder named 12, and so on. Now I found the solution by adding .replace(f.split(".")[2], "") to the folder:

folder = "C:\Folder"+"/"+f.split(".")[1].replace(f.split(".")[2], "").

Now I would like to replace the folder names 01, 12 by their State abbreviations. I have created a dictionary st_name = { '01' : 'AL','12': 'FL'}, but I have no idea how to use it. Is there a better way to do this?

import os
import shutil
import sys
dr = sys.argv[1]; files = os.listdir("C:\Folder")
for f in [f for f in files if os.path.isfile ("C:\Folder"+"/"+f)]:
    folder = "C:\Folder"+"/"+f.split(".")[1]
    if not os.path.exists(folder):
        os.makedirs(folder)
    shutil.move("C:\Folder"+"/"+f, folder+"/"+f)

Upvotes: 0

Views: 34

Answers (1)

kabanus
kabanus

Reputation: 25895

Apply your mapping by using the dictionary you created:

folder = "C:\Folder"+"/"+st_name[f.split(".")[1]]

Upvotes: 1

Related Questions