Reputation: 1344
I have a list of strings which contains files like below
filename = [ '000101 FL - Project Title Page.DOC',
'014200 FL - References.DOC',
'095446 FL - Fabric-Wrapped Ceiling Panels.DOC',
'142113 FL - ELECTRIC TRACTION FREIGHT ELEVATORS.DOC']
I want to check if a folder with a name consisting of Div + first two numbers in each string exist, such as Div00, Div01, Div09, Div14 in this case. If not I would like to create this folder. Then store the name of the file in this folder.
In pseudocode I believe it would be similar to
for file in filenames
if 'Div' + file[0][0] not a folder
make folder 'Div' + file[0][0]
add file to folder
else
add file to folder Div + file[0][0]
There will be multiple files starting with the same two numbers this is why I want to sort them into folder.
Let me know if you need any clarification.
Upvotes: 2
Views: 504
Reputation: 18007
Use os.mkdir
to create a directory and shutil.copy2
to copy a file,
import os
import shutil
filenames = [ '000101 FL - Project Title Page.DOC']
for filename in filenames:
folder = 'Div' + filename[:2] # 'Div00'
# Create the folder if doesn't exist
if not os.path.exists(folder):
os.makedirs(folder)
# Copy the file to `folder`
if os.path.isfile(filename):
shutil.copy2(filename, folder) # metadata is copied as well
Upvotes: 1
Reputation:
Try something like this:
import os
import shutil
for file in filenames
dir_name = "Div%s" % file[0:2]
if not os.path.isdir(dir_name)
os.makedirs(dir_name)
shutil.copy(file, dir_name)
Upvotes: 0
Reputation: 71
You can just check if there is a folder and make it if it does not exist
if not os.path.exists(dirName):
os.makedirs(dirName)
Upvotes: 1