python实现文件复制转移_Python 文件复制转移

参考链接

说明

下面先是 对比文件名和大小是否一致,不一致则替换。目标文件夹没有则直接拷贝

并且在目标文件夹追加了一个log.txt日志

import shutil

import os

import time

# sourcefile:源文件路径 fileclass:源文件夹 destinationfile:目标文件夹路径

def copy_file(sourcefile, destinationfile,logTxt=""):

logTxt=(logTxt,os.path.join(destinationfile, "log.txt"))[len(logTxt)==0];

# 遍历目录和子目录

for filenames in os.listdir(sourcefile):

# 取得文件或文件名的绝对路径, os.path.join 把目录和文件名合成一个路径

filepath = os.path.join(sourcefile, filenames)

# 判断是否为文件夹

if os.path.isdir(filepath):

copy_file(filepath, destinationfile + '/' + filenames,logTxt)

# 判断是否为文件

elif os.path.isfile(filepath):

# print('Copy %s'% filepath +' To ' + destinationfile)

# 如果无文件夹则重新创建

if not os.path.exists(destinationfile):

os.makedirs(destinationfile)

# 判断是否存在文件,且文件大小一致

destinationfilePath = os.path.join(destinationfile, filenames)

# 判断是否存在文件

if os.path.exists(destinationfilePath):

# 对比文件大小和文件名,如果不一致则替换

if not (os.path.basename(filepath)==os.path.basename(destinationfilePath) and os.path.getsize(filepath)==os.path.getsize(destinationfilePath)) :

writeTxt(logTxt,filepath+"\t与\t"+destinationfilePath + " 不相同,将替换")

print(logTxt,filepath+"\t与\t"+destinationfilePath + " 不相同,将替换")

shutil.copy(filepath, destinationfile)

else:

writeTxt(logTxt,filepath+"\t与\t"+destinationfile+" 无相同文件,则拷贝")

print(logTxt,filepath+"\t与\t"+destinationfile+" 无相同文件,则拷贝")

shutil.copy(filepath, destinationfile)

def writeTxt(path,message):

with open(path,'a') as f: # a是追加,如果不存在则创建文件

f.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"\t"+message+'\n')

copy_file("D:/old", "D:/new","D:/new/log.txt")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值