【发布时间】:2019-01-25 11:54:47
【问题描述】:
我在文件夹源中有 130 个文件,我想将每个文件复制到单个文件夹 001、002、003 ... 130(所有这 130 个文件夹都位于目标文件夹中)。
这样每个文件夹都只包含一个文件。 我想出了这个,但可能有点凌乱和多余......而且大多数情况下它不起作用。
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)
【问题讨论】:
-
你在用python2吗?
-
我使用的是 Python 3.6.7
-
您在此问题中使用的字符串格式通常用于 python2,尽管它不推荐用于 python3。从 Python 3.6 版本开始,有可用的 f-string 格式,看起来更方便。