import os
import shutil
import math
import time
import datetime
# 生成局域网共享盘某文件夹及其子文件夹中的文件目录,并将指定类型的文件复制到本地文件夹中,并生成日志
path_src = r'S:\2 培训' # 局域网共享盘某文件夹
path_dst_localDisk = r'C:\培训资料_Copy\资料' # 本地文件夹
copy_PathFile_all = r'c:\培训资料_Copy\培训资料目录.txt'
copy_log_all = r'c:\培训资料_Copy\培训资料目录_对应_all.txt'
copy_log_add = r'c:\培训资料_Copy\培训资料目录_对应_add.txt'
# if os.path.exists(fullFilename_local): # 判断否存在输入的子文件夹
# print('文件夹已经存在')
# if os.path.getsize(fullFilename_local):
# shutil.rmtree(fullFilename_local) # 首次运营,清空下面所有文件夹及文件
# print('已经清空下面所有文件夹及文件')
# os.mkdir(fullFilename_local)
# else:
# os.mkdir(fullFilename_local)
if not os.path.exists(path_dst_localDisk): # 判断本地文件夹是否存在
os.mkdir(path_dst_localDisk)
current_time = datetime.datetime.now()
print("current_time:" + str(current_time))
T1 = time.clock()
file_all_PathAndFile = open(copy_PathFile_all,'w', encoding='utf-8')
file_all = open(copy_log_all,'w', encoding='utf-8')
file_add = open(copy_log_add,'w', encoding='utf-8')
num_all = 0
num_old = 0
num_add = 0
label = '_00_'
num_src = 0
for root, dirs ,files in os.walk(path_src): # 对于每一个层级,返回其路径、该路径下面的文件夹、该路径下面的所有路径
print('root:')
print(root)
print('dirs:')
print(dirs)
print('files:')
print(files)
for dirname in dirs:
fullDirname_each =os.path.join(root, dirname)
print(fullDirname_each)
num_src +=1
file_all_PathAndFile.write('\n'+str(num_src) +' '+ fullDirname_each)# 输出原始目录下的所有文件夹
for filename in files:
fullFilename_each =os.path.join(root, filename)# 输出原始目录下的所有文件
print(fullFilename_each)
num_src +=1
file_all_PathAndFile.write('\n'+str(num_src) +' '+ fullFilename_each)
if '.mp4' in filename or '.avi' in filename or '.ppt' in filename or '.pdf' in filename or '.doc' in filename:
fullFilename_src = os.path.join(root,filename)
print('/*\n'+fullFilename_src)
fullFilename_dst = os.path.join(path_dst_localDisk,filename)
num_all += 1
if not os.path.exists(fullFilename_dst):
if not filename.startswith('~$'): # 跳过打开文件时产生的缓存文件
label = '_isAdd_'
shutil.copy(fullFilename_src,path_dst_localDisk)
print('在本地路径下不存在该文件,需要复制')
num_add += 1
print(str(num_add)+label)
logLine_add = '\n' + str(num_all)+' '+str(current_time) +' '+ label +' '+ fullFilename_src + ' '+fullFilename_dst
file_add.write(logLine_add)
else:
label = '_isExist_'
print('在本地路径下已经存在该文件,不需要复制')
num_old += 1
print(str(num_old)+label)
print('[old_'+str(num_old)+',add_'+str(num_add)+',all_'+str(num_all)+']')
current_time = datetime.datetime.now()
logLine = '\n' + str(num_all)+' '+str(current_time) +' '+ label +' '+ fullFilename_src + ' '+fullFilename_dst
print(logLine)
file_all.write(logLine)
print('*/\n')
file_all_PathAndFile.close;
file_all.close;
file_add.close;
os.startfile(path_dst_localDisk)
T2 =time.clock()
print("运行时间:", round(T2-T1,3), "秒")
print('Done...')
1、生成局域网共享盘某文件夹及其子文件夹中的文件目录,并将指定类型的文件复制到本地文件夹中,并生成日志。
2、后续每次重复运行时,只会复制原目录下新增加的文件,并生成日志。
附:
Python3.8.2下载地址 https://www.python.org/downloads/
Pycharm官方下载地址 https://www.jetbrains.com/pycharm/download/
3、运行后效果: