通过Python实现文件单独存放
在一个文件夹中有许多的单独文件,如果我们需要将其单独放在文件自己的文件夹中,可以通过这种方式。
比如下图这样的结果,将“Pictures”文件夹中的每个文件夹里的图片,单独放到“Results”文件中。
实现
一共有两种迭代,一种是文件夹中的文件,另一种是文件夹中的文件夹中的文件(此为一类)。
文件夹中还有文件夹的情况
目录结构如图所示。
我将代码放到了文件的同级目录,具体可以根据自己的需要修改。
# 文件夹下的文件夹中的文件。
import os,shutil
#获取当前执行文件的目录。
currentPath=os.getcwd()
#目标文件所在的目录。
src_path=currentPath + '/Pictures/'
while True:
fold_list=os.listdir(src_path) # 得到目标文件夹的所有子目录。
if len(fold_list)>0:
for fold in fold_list: # 迭代所有的子目录,fold就是子目录的名字。
file_list = os.listdir(src_path + fold) # 判断子目录中是否有文件。
if len(file_list)>0:
for file in file_list: #迭代所有文件
# 拆解文件和后缀,保证新建的文件夹不包含后缀。
name, suffix = os.path.splitext(file)
# 目标目录,可以根据自己的需要修改。
target_path = currentPath + '/Results/' + fold + '/' + name + '/'
# 判断是否有了当前文件。
newFolder = os.path.exists(target_path)
if (not newFolder):
os.makedirs(target_path)
# 复制文件
shutil.copy(src_path+ '/' + fold + '/' + file, target_path + file)
print(fold, " Has Done!")
break
文件夹中的文件
这一步只需要将代码中的子目录文件夹迭代去掉就好了。
效果如下图所示。
import os,shutil
currentPath=os.getcwd()
src_path=currentPath + '/NoChilds/'
while True:
file_list = os.listdir(src_path)
if len(file_list) > 0:
for file in file_list:
# New Floder.
name, suffix = os.path.splitext(file)
target_path = currentPath + '/Results/' + 'NoChilds/'+ name + '/'
newFolder = os.path.exists(target_path)
if (not newFolder):
os.makedirs(target_path)
shutil.copy(src_path + '/' + file, target_path + file)
print("This Fold Has Done!")
break
希望对大家有所帮助,互相学习。