zoukankan      html  css  js  c++  java
  • 【python----发轫之始】【实现文件备份】

    import os
    import os.path
    
    
    class FileBackup(object):
        """
        对文件进行备份
        """
    
        def __init__(self, src, dist):
            """
            构造函数
            :param src: 原地址
            :param dist: 备份地址
            """
            self.src = src
            self.dist = dist
    
        def read_src(self):
            """
            读取src目录下所有的文件
            :return:
            """
            ls = os.listdir(self.src)
            for l in ls:
                self.back_up(l)
    
        def back_up(self, src):
            """
            对传输过来的文件进行检查通过则备份
            :param src: 带检测是否备份的文件
            :return:
            """
            #判断是否有要备份到的地方的地址,无,就创建。
            if not os.path.exists(self.dist):
                os.makedirs(self.dist)
                print("所备份到的地址不存在,已创建成功!")
    
            #拼接完整路径,便于区分文件与文件夹
            full_src_path = os.path.join(self.src, src)
            full_dist_path = os.path.join(self.dist, src)
    
            # 检测是否符合备份要求
            if os.path.isfile(full_src_path) and os.path.splitext(full_src_path)[-1].lower() == '.txt':
                print("文件{0}符合备份要求,正在备份......".format(src), end='')
    
                with open(full_src_path, 'r', encoding='utf-8') as f_src:
                    with open(full_dist_path, 'w', encoding='utf-8') as f_dist:
                        print("正在读取......正在写入......", end='')
    
                        while True:
                            rest = f_src.read(100)
                            if not rest:
                                break
                            f_dist.write(rest)
                        f_dist.flush()
                        print("备份完成!")
            else:
                print("文件不符合要求,正在跳过......")
    
    
    if __name__ == "__main__":
        # 获得当前文件的地址(去除当前文件名的地址)
        base_path = os.path.dirname(os.path.abspath(__file__))
        # 将文件地址与我们要备份的地址拼接在一起。
        src_path = os.path.join(base_path, 'src')
        print("您要备份的地址为:{0}".format(src_path))
        dist_path = os.path.join(base_path, 'dist')
        print("将要备份到的地址为:{0}".format(dist_path))
    
        # 获得面向对象函数
        bak = FileBackup(src_path, dist_path)
        bak.read_src()
  • 相关阅读:
    获取Mysql-jdbc驱动Driver类的两种方式
    Misha and Changing Handles
    What Are You Talking About (map)
    Let the Balloon Rise <map>的应用
    ignitius and princess 2(全排列)
    大一下学期计划
    大一上学期总结
    algorithm的基本注意事项
    STL的注意事项
    STL的基本操作指令
  • 原文地址:https://www.cnblogs.com/Attacking-vincent/p/12961173.html
Copyright © 2011-2022 走看看