Python实现文件备份

在这里插入图片描述

# -*- encoding: utf-8 -*-
"""
@File    : backup_test.py
@Time    : 2020/10/19 16:56
@Author  : XUDA
@Email   : gudianpai@qq.com
@Software: PyCharm
"""
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_files(self):
        """
        读取src目录下的所有文件
        :return:
        """
        ls = os.listdir(self.src)
        print(ls)
        for l in ls:
            #self.backup_file(l)
            self.backup_file_Optimized_Edition(l)

    def backup_file(self, file_name):
        """
        处理备份
        :param file_name:文件/文件夹的名称
        :return:
        """
        # 1. 判断dist是否存在,如果不存在,要创建这个目录
        if not os.path.exists(self.dist):
            os.makedirs(self.dist)
            print('指定目录不存在,创建完成')
        # 2. 判断文件是否为我们要备份的文件,可以借助后缀名进行判断
        # 拼接文件的完整路径
        full_src_path = os.path.join(self.src, file_name)
        full_dist_path = os.path.join(self.dist, file_name)
        # 首先要判断是否为文件,然后借助文件的后缀名进行判断
        if os.path.isfile(full_src_path) and os.path.splitext(full_src_path)[-1].lower() == '.txt':
            print(full_src_path)
            # 3. 读取文件内容
            with open(full_dist_path, 'w', encoding='utf-8') as f_dist:
                print('>>开始备份【{0}】'.format(file_name))
                with open(full_src_path, 'r', encoding='utf-8') as f_src:
                    while True:
                        rest = f_src.read(100)
                        if not rest:
                            break
                        # 4. 把读取到的内容写入到新的文件中
                        f_dist.write(rest)
                    f_dist.flush()
                print('>>【{0}】备份完成'.format(file_name))
        else:
            print("文件类型不符合备份要求,跳过>>")

        # def main():
        # # 要备份的文件目录地址
        # # src_path = 'E:\\py-learn\\chapter04\\src'
        # # # 备份后的目录地址
        # # dist_path = 'E:\\py-learn\\chapter04\\dist'
        # # 当前代码的目录名称
        # # E:\py-learn\chapter04\backup_test.py
        # base_path = os.path.dirname(os.path.abspath(__file__))
        # # 要备份的目录地址
        # src_path = os.path.join(base_path, 'src')
        # # 备份后的目录地址
        # dist_path = os.path.join(base_path, 'dist')
        #
        # print(src_path)
        # print(dist_path)
        # bak = FileBackup(src_path, dist_path)
        # bak.read_files()
    def backup_file_Optimized_Edition(self, file_name):
            """
            处理备份-优化
            :param file_name:文件/文件夹的名称
            :return:
            """
            """
                    处理备份
                    :param file_name:文件/文件夹的名称
                    :return:
                    """
            # 1. 判断dist是否存在,如果不存在,要创建这个目录
            if not os.path.exists(self.dist):
                os.makedirs(self.dist)
                print('指定目录不存在,创建完成')
            # 2. 判断文件是否为我们要备份的文件,可以借助后缀名进行判断
            # 拼接文件的完整路径
            full_src_path = os.path.join(self.src, file_name)
            full_dist_path = os.path.join(self.dist, file_name)
            # 首先要判断是否为文件,然后借助文件的后缀名进行判断
            if os.path.isfile(full_src_path) and os.path.splitext(full_src_path)[-1].lower() == '.txt':
                print(full_src_path)
                # 3. 读取文件内容
                with open(full_dist_path, 'w', encoding='utf-8') as f_dist,\
                    open(full_src_path, 'r', encoding='utf-8') as f_src:
                    print('>>开始备份【{0}】'.format(file_name))
                    while True:
                        rest = f_src.read(100)
                        if not rest:
                            break
                        # 4. 把读取到的内容写入到新的文件中
                        f_dist.write(rest)
                    f_dist.flush()
                    print('>>【{0}】备份完成'.format(file_name))
            else:
                print("文件类型不符合备份要求,跳过>>")

def main():
    base_path = os.path.dirname(os.path.abspath(__file__))
    # 要备份的目录地址
    src_path = os.path.join(base_path, 'src')
    # 备份后的目录地址
    dist_path = os.path.join(base_path, 'dist')
    bak = FileBackup(src_path, dist_path)  # 不是函数,而是对类的初始化
    bak.read_files()  # 这个是调用的函数


if __name__ == '__main__':
    main()
"""
遇到的bug
Traceback (most recent call last):
  File "E:/py-learn/chapter07/backup_test.py", line 94, in <module>
    bak.read_files()
  File "E:/py-learn/chapter07/backup_test.py", line 32, in read_files
    self.backup_file(l)
  File "E:/py-learn/chapter07/backup_test.py", line 52, in backup_file
    with open(full_dist_path, 'r', encoding='utf-8') as f_dist:
FileNotFoundError: [Errno 2] No such file or directory: 'E:\\py-learn\\chapter07\\dist\\file1.txt'
"""
# 55行 读写模式书写错误 应该 r>>>w

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值