[英]How can I copy files from a folder into multiple folders
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). 我在文件夹源中有130个文件,我想将每个文件复制到一个文件夹001、002、003 ... 130中(所有这130个文件夹都位于目标文件夹中)。
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. for idx, f in enumerate(files):
在循环时对文件进行计数,因此您知道文件的索引。 To get the destination, the idx is used as directory name. 为了获得目的地,将idx用作目录名。 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). 我假设您知道方法format
{d:03d}
只是说,分配给d的值应为3个字符长,该值是一个整数,并用零填充(例如003)。 Of course, this code assumes that you do not have 1000+ files, in that case, just increase the number of zeroes. 当然,此代码假定您没有1000多个文件,在这种情况下,只需增加零的数量即可。 You could for example calculate the log10
-value of the number of files to get the number of zeros you have to add. 例如,您可以计算文件数量的log10
值,以获取必须添加的零数量。
First of all, I would rather use shutil.copy
if I wanted to copy the files, but not to move. 首先,如果我想复制文件而不移动,则宁愿使用shutil.copy
。 Though, the main idea does not depend on it. 虽然,主要思想并不依赖于此。 Also you don't need no if
statements here as well as the inner cycle: 另外,这里不需要if
语句以及内部循环:
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.