"""
@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_Optimized_Edition
(l
)
def backup_file(self
, file_name
):
"""
处理备份
:param file_name:文件/文件夹的名称
:return:
"""
if not os
.path
.exists
(self
.dist
):
os
.makedirs
(self
.dist
)
print('指定目录不存在,创建完成')
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
)
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
f_dist
.write
(rest
)
f_dist
.flush
()
print('>>【{0}】备份完成'.format(file_name
))
else:
print("文件类型不符合备份要求,跳过>>")
def backup_file_Optimized_Edition(self
, file_name
):
"""
处理备份-优化
:param file_name:文件/文件夹的名称
:return:
"""
"""
处理备份
:param file_name:文件/文件夹的名称
:return:
"""
if not os
.path
.exists
(self
.dist
):
os
.makedirs
(self
.dist
)
print('指定目录不存在,创建完成')
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
)
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
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'
"""
转载请注明原文地址: https://lol.8miu.com/read-13116.html