功能:
1、获取目录下所有文件路径
2、指定目录下查找指定文件,存在则返回绝对路径
3、复制多个文件到指定目录
4、将源目录origindir所有文件包括子目录,复制到savedir
# !/usr/bin/env python
# -*-coding:utf-8 -*-
import os,json,shutil,time
def getRootPath():
"""获取项目的根目录"""
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = curPath[:curPath.find("Projectname\\")+len("Projectname\\")]
return rootPath
def getOtherPath(relpath):
"""项目Projectname的根目录下,补充相对路径为绝对路径"""
rootPath = getRootPath()
abspath = os.path.abspath(rootPath+relpath)
return abspath
def get_allfilepaths(dirpath):
"""返回目录dirpath下所有文件路径"""
filepaths = []
for root, dirs, files in os.walk(dirpath, topdown=True):
for f in files:
filepaths.append(os.path.join(root, f))
filepaths.sort()
return filepaths
def search_file_abspath(dirpath,filename):
"""在目录dirpath中查找filename文件,存在则返回绝对路径filepath,不存在则返回None"""
filepath = None
for root, dirs, files in os.walk(dirpath, topdown=True):
if filename in files:
filepath = os.path.join(root, filename)
break
return filepath
def copy_files(filepaths,savedir):
"""复制文件到指定目录,将filepaths复制保存到savedir目录中"""
if not os.path.exists(savedir): # savedir不存在,则递归创建
os.makedirs(savedir)
L = len(filepaths)
start = time.perf_counter()
for filepath in filepaths:
i = filepaths.index(filepath) + 1
filename = os.path.basename(filepath)
n_filepath = os.path.join(savedir, filename)
if not os.path.exists(n_filepath):
shutil.copy(filepath, n_filepath)
a, b = int(i / L * 50), int((L - i) / L * 50)
print("\r有效路径共{}个,已复制{}个,进度:{:^3.0f}%<{}>{}{:.2f}s".format(L,i,(i / L) * 100, "▋" * a, "-" * b,time.perf_counter() - start),end="")
def copy_dirs(origindir,savedir):
"""将源目录origindir所有文件包括子目录,复制到savedir"""
# 获取origindir下所有文件路径
filepaths = []
for root, dirs, files in os.walk(origindir, topdown=True):
for f in files:
filepaths.append(os.path.join(root, f))
if not os.path.exists(savedir): # savedir不存在,则递归创建
os.makedirs(savedir)
L = len(filepaths)
start = time.perf_counter()
for filepath in filepaths:
i = filepaths.index(filepath) + 1
relpath = filepath[len(origindir):]
n_filepath = savedir+relpath
if not os.path.exists(os.path.dirname(n_filepath)):
os.makedirs(os.path.dirname(n_filepath))
if not os.path.exists(n_filepath): # savedir中不存在,copy
shutil.copy(filepath, n_filepath)
a, b = int(i / L * 50), int((L - i) / L * 50)
print("\r有效路径共{}个,已复制{}个,进度:{:^3.0f}%<{}>{}{:.2f}s".format(L,i,(i / L) * 100, "▋" * a, "-" * b,time.perf_counter() - start),end="")
if __name__ == '__main__':
nasdir = r'F:\origindir'
savedir = r'F:\savedir'
copy_dirs(nasdir,savedir)
版权声明:本文为m0_37586703原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。