Python 文件同步脚本
2014-04-22 16:17
363 查看
#-*- coding: utf-8 -*- import os import shutil import sys list = sys.argv source_folder = list[1]# 源 文件夹 target_folder = list[2] # 目标 文件夹 def syncdir(source_folder, target_folder): """ 这里递归同步每一个文件夹下的文件 """ if(not os.path.exists(target_folder)): # 目标文件夹不存在,就先建一个出来 os.mkdir(target_folder) for file in os.listdir(source_folder): # 遍历 源文件夹下的所有文件(包括文件夹)。用os.path.walk,或许会更方便些,那样递归都省去了。 from_file = os.path.join(source_folder, file) to_file = os.path.join(target_folder, file) if(os.path.isdir(from_file)): # 如果是文件夹,递归 syncdir(from_file, to_file) else: if(iscopy(from_file, to_file)): # 看是否需要拷贝 shutil.copy2(from_file, target_folder) # 执行copy。。。 # print("copy " + file + " from " + from_file + " to " + to_file + ";") # print("copy", file, "from", from_file, "to" , to_file , ";") print("copy %s from %s to %s;" % (file , from_file , to_file)) # 上面注释掉的2种写法都对。现在用的这种,更像是一句话。。。 else: print("The file %s is exist" % to_file) def iscopy(from_file, to_file): ''' 决断 是否 需要 拷贝。如果需要,返回True,否则返回False ''' if(not os.path.exists(to_file)): # 目标文件还不存在,当然要拷过去啦 return True from_file_modify_time = round(os.stat(from_file).st_mtime, 1) # 这里精确度为0.1秒 to_file_modify_time = round(os.stat(to_file).st_mtime, 1) # 拿到 两边文件的最后修改时间 if(from_file_modify_time > to_file_modify_time): # 比较 两边文件的 最后修改时间 return True return False if __name__ == '__main__': ''' 这里是传说中的 主入口 ''' # if(not os.path.exists(source_folder) or not os.path.isdir(source_folder)): if(not os.path.isdir(source_folder)): # 发现第一个条件没有,也是一样的 print("The source folder:%s is not exist" % source_folder) sys.exit() # 这个时候,就要退出江湖了。。。最初写的时候,敲了个return,哈哈。。。 syncdir(source_folder, target_folder) # 这里是 同步的入口 print("All files has been sync")
相关文章推荐
- 使用Fabric模块编写的批量同步文件的python脚本
- Python中在脚本中引用其他文件函数的实现方法
- Linux 系统 svn批量新建钩子脚本和解决不能同步中文名文件
- python脚本:根据视差图制作npy格式的深度信息文件
- Python备份文件目录脚本
- expect脚本同步文件、指定host和要同步的文件、构建文件分发系统、批量远程执行命令
- python脚本文件批量改名
- 用python编写脚本从wireshark导出的数据文件中提取数据
- 用pyinstaller把python脚本生成.exe文件
- 使用Python脚本将酷狗音乐的缓存文件修改为可播放
- 恢复百度云盘本地误删的文件脚本---python
- C调用Python脚本文件里的函数
- python脚本检查文件内容
- Python脚本完美解决Linux环境解压.zip文件乱码问题
- python脚本――自动推送txt,EXCEL等文件模板
- 将Python脚本打包成可执行文件
- Windows平台使用PyInstaller将Python脚本打包成可执行文件
- linux下python脚本文件的执行与编码解析
- atitit.提升备份文件复制速度(3) ----建立同步删除脚本
- Python实现删除当前目录下除当前脚本以外的文件和文件夹实例