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?
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]
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.
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)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.