I have 130 files in a folder source and I want to copy each files in a single folder 001, 002, 003 ... 130 (all these 130 folders are located in destination folder).
So that every folder contain just one file. I came up with this but probably it's a bit messy and redundant... and mostly it doesn't work.
import shutil
import os
source = '/Users/JohnCN/photo_database/mugshot_frontal/'
files = os.listdir(source)
for i in files:
for fold in range(1,131):
if fold<10:
destination = "/Users/JohnCN/photo_DBsorted/00%s" %fold
shutil.move(source+i, destination)
elif fold in range(10,100):
destination = "/Users/JohnCN/photo_DBsorted/0%s" %fold
shutil.move(source+i, destination)
else:
destination = "/Users/JohnCN/photo_DBsorted/%s" %fold
shutil.move(source+i, destination)
I would do it the following way:
import shutil
import os
source = '/Users/JohnCN/photo_database/mugshot_frontal/'
files = os.listdir(source)
for idx, f in enumerate(files):
destination = '/Users/JohnCN/photo_DBsorted/{d:03d}'.format(d=(idx + 1))
shutil.move(source + f, destination)
So, what does it do? for idx, f in enumerate(files):
counts the files while looping, so you know the index of the file. To get the destination, the idx is used as directory name. I assume you know the method format
, {d:03d}
simply says, that the value d is assigned to should be 3 characters long, the value is an integer and it's padded with zeros (eg 003). Of course, this code assumes that you do not have 1000+ files, in that case, just increase the number of zeroes. You could for example calculate the log10
-value of the number of files to get the number of zeros you have to add.
First of all, I would rather use shutil.copy
if I wanted to copy the files, but not to move. Though, the main idea does not depend on it. Also you don't need no if
statements here as well as the inner cycle:
files = os.listdir(source)
for i in range(len(files)):
file = os.path.join(source, files[i])
shutil.copy(file, os.path.join(source, '%03d'%i, files[i])
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.