I have many files, for example like this:
I want to move these files into folders according to their similar names, for example:
_form into the _form folder
,
_gallery into the _gallery folder
,
75_gallery into the 75_gallery folder
, and
75_gallery_from_home to 75_gallery_from_home folder
.
I'm trying to understand that the files are the same until before the _number
part appears, I don't know how to split the filenames and then move them to their respective folders. kindly help me
CodePudding user response:
You can use the following script to extract the corresponding folder names, create the folders and also to move files into the folders in one go.
import os
import re
import shutil
pattern = "_[0-9] "
file_names = os.listdir(".")
for file_name in file_names:
split = re.split(pattern, file_name)
if len(split) == 1:
print(f"Cannot extract the corresponding folder name from file {file_name}.")
else:
folder_name = split[0]
if not os.path.exists(folder_name):
os.mkdir(folder_name)
shutil.move(file_name, os.path.join(folder_name, file_name))
The regex pattern allows you to split the filename on the first underscore that is followed by any number.
CodePudding user response:
You can use the below as a starting point for your solution. Assuming you have excluded the file extension and just have filename in a variable, the below code shows how to use regex
to get the initial part of filename so that you
can frame the folder name to move the file to.
import re
filename = "75_gallery_2686WYWENDD"
x = re.split("_", filename)
str=''
for k in x:
if(re.search("^[0-9][0-9]",k)):
if(len(k)>2):
#ignore this part of file name
print('ignoring ' k)
else:
str = str k
else:
str = str '_' k
print('folder name : ' str)