I have a folder with many files named like homeXXX_roomXXX_high.csv or homeXXX_roomXXX_low.csv, where the XXX part is replaced with a three-digit number.
I want to use some code to move the files into separate folders based on the number next to "home" in the filename. For example, I want to specify that files with names starting home101, home103, home320, home553, etc. should all be moved into folder A whereas those starting with home555, home431, home105 should go to FolderB.
I have this code so far:
import shutil
import os
source = '/path/to/source_folder'
dest1 = '/path/to/FolderA'
dest2 = '/path/to/FolderB'
files = os.listdir(source)
for f in files:
if (f.startswith("home101") or f.startswith("home103")):
shutil.move(f, dest1)
elif (f.startswith("home431") or f.startswith("home555")):
shutil.move(f, dest2)
However, it's tedious to specify all the if and else cases. I'd like to use some kind of structured data, such as a list, to specify groups of "home" numbers and the corresponding folder paths. How can I do this in Python?
it seems like you can use another for, it would look something like this:
You can also create a function:
and the code will get cleaner because you avoid repetition :)