Python实现文件备份操作

Python实现文件备份操作

# 1.用户输入目标文件
old_name = input("请输入你要备份的文件名: ")


# 2.规划备份文件名字
# 2.1提取后缀 -- 找到名字中的点 -- 名字和后缀分离 -- 最右侧的点才是后缀的点 --查找某个字符串
index = old_name.rfind('.')
# print(index)

# 有效文件名才备份
if index > 0:
    # 提取后缀
    postfix = old_name[index:]

# 2.2组织新名字 = 原名字 + [备份] + 后缀
new_name = old_name[:index] + '[备份]' + postfix
# print(new_name)


# 3.备份文件写入数据(数据和原文件一样)
# 3.1 打开原文件和备份文件
old_f = open(old_name, 'rb')
new_f = open(new_name, 'wb')
# 3.2 原文件读取,备份文件写入
while True:
    content = old_f.read(1024)
    if len(content) == 0:
        break
    new_f.write(content)
# 3.3 关闭文件
old_f.close()
new_f.close()

    原文作者:活得潇潇洒洒CL
    原文地址: https://blog.csdn.net/weixin_43426381/article/details/105663217
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞