Reputation: 1194
My list has 15 items, all of them contains the word '_new' in the end. So I want to create folders with names of the items without '_new' in it. How to do it?
Upvotes: 1
Views: 5903
Reputation: 4462
Use strip method with list comprehension to remove "_new":
import os
path = r"C:\Program Files\mypath"
[os.makedirs(os.path.join(path,str(name.strip("_new"))) for name in name_list if os.path.exists(path)]
Upvotes: 0
Reputation: 142206
I'll go for the regex then:
import re
new = [re.sub('_new$', '', fname) for fname in your_list]
However you correct your name, you'll want to use os.mkdir to create it.
Upvotes: 1
Reputation: 1123510
Use a list comprehension to remove the last 4 characters:
[name[:-4] for name in list_of_names]
If only some of the names contain _new
at the end, use a conditional expression:
[name[:-4] if name.endswith('_new') else name for name in list_of_names]
Upvotes: 8