import os
import shutil
遍历所有文件夹,获取对应格式的文件数据,并复制整理到不同的文件夹
def GetDirectory(path):
"""
:param path: root_path 文件夹树的非叶子节点
:return: 完整的文件相对路径列表
"""
directory=os.listdir(path)
directory_list=[]
for dirs in directory:
if not os.path.isfile(os.path.join(path,dirs)):
directory_list.append(os.path.join(path,dirs))
return directory_list
def GetFile(path):
"""
:param path: 文件夹树的叶子节点
:return: 在叶子节点中保存的所有文件名词
"""
files=os.listdir(path)
file_list=[]
for file in files:
if os.path.isfile(os.path.join(path,file)):
file_list.append(os.path.join(path,file))
return file_list
遍历文件夹下的所有文件https://www.csdn.net/tags/OtTagg1sOTc3MDQtYmxvZwO0O0OO0O0O.html
Python学习笔记(20)-文件和文件夹的移动、复制、删除、重命名
https://blog.csdn.net/woshisangsang/article/details/74360612
pdf_path = "PDF/"
ppt_path = "PPT/"
path=r"dataset"
a=GetFile(path)
b=GetDirectory(path)
print(path,"*根目录文件夹内容(所有的孩子节点):")
for name in b:
print("child ",os.path.join(name))
for name in a:
print("当前节点的信息 attribution",os.path.join(name))
dataset *根目录文件夹内容(所有的孩子节点):
child dataset\10072-朱
child dataset\105008_徐
child dataset\105045+刘
child dataset\105054-李
child dataset\105060-王
os.walk 方法:
os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。
os.walk() 方法是一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。
os.walk(top[, topdown=True[, οnerrοr=None[, followlinks=False]]])
参数
top – 是你所要遍历的目录的地址,
topdown --可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启)。如果 topdown 参数为 True,walk 会遍历top文件夹,与top 文件夹中每一个子目录。
onerror -- 可选,需要一个 callable 对象,当 walk 需要异常时,会调用。
followlinks -- 可选,如果为 True,则会遍历目录下的快捷方式(linux 下是软连接 symbolic link )实际所指的目录(默认关闭),如果为 False,则优先遍历 top 的子目录。
返回值: 返回生成器. 需要 for 循环调用 生成 root , dirs , files
返回的是一个三元组(root,dirs,files). 简单理解就是返回当前文件夹节点的信息
root 所指的是当前正在遍历的这个文件夹的本身的地址, 也就是父亲节点
dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录),也就是孩子节点
files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录),也就是当前节点的值
""" 将文件夹子树 中的pdf pptx 文件分别复制移动到对应文件夹"""
for root,dirs,files in os.walk(path,topdown=True):
for name_dir in dirs:
a=GetFile(os.path.join(root,name_dir))
b=GetDirectory(os.path.join(root,name_dir))
for name_file in a:
file_path = os.path.join(name_file)
if file_path.endswith(".pdf"):
shutil.copy2(file_path,pdf_path )
elif file_path.endswith(".pptx"):
shutil.copy2(file_path, ppt_path)