Reputation: 706
I am reading all files from a directory and storing the file paths of those in that directory in a list using
files = [os.path.abspath(x) for x in os.listdir(r"my directory")]
Each file in a unique template so the resulting list is something like
[C:\Users\....\Template_Coversheet.xlsx
C:\Users\....\Template_Blanks.xlsx,
C:\Users\....\Template_Stocks.xlsx,
C:\Users\....\Template_May.xlsx]
*Note files aren't necessarily always in the same order
I want to reach each of these files and assign them to a variable that corresponds to the type of template.
I can do this by doing a a for loop and a long series of if statements
for f in files:
if "Blanks" in f:
blank=f
if "Stocks" in f:
stock=f
if "May" in f:
may=f
if "Coversheet" in f:
coversheet=f
But is there an easier or more pythonic way to achieve this?
Upvotes: 0
Views: 38
Reputation: 79
First, if this depends only on the file name, you can use that instead of the whole path. You can use regular expressions if the patterns are complex. But in your case and if it's just Template_TEMPLATENAME.xlsx
you can create a dictionary and map TEMPLATENAME
to the full name. The code would be something like this:
import os
mapping = dict()
for file in os.listdir():
mapping[file.replace(".xlsx", "").split("-")[-1]] = file
For such a list:
Template_A.xlsx
Template_B.xlsx
Template_Foo.xlsx
You will have:
{
"A": "Template_A.xlsx",
"B": "Template_B.xlsx",
"Foo": "Template_Foo.xlsx"
}
Upvotes: 2
Reputation: 71562
Replace all your individual variables with a dict, and then you can do something like:
TEMPLATE_TYPES = "Blanks", "Stocks", "May", "Coversheet"
files_by_template = {t: [] for t in TEMPLATE_TYPES}
for f in files:
for t in TEMPLATE_TYPES:
if t in f:
files_by_template[t].append(f)
Upvotes: 0