python文件操作练习之文件备份

  文件备份

## 文件备份
# 打开文件
def backup(file1, file2):
    with open(file1, 'rb') as f1,
     open(file2, 'wb') as f2:
        content = f1.read()
        f2.write(content)

## 目录备份
import os

# 获取目录中的所有文件、目录
def dict_backup(dict_file, back_file):
    all_files = os.listdir(dict_file)    # 获取要备份目录中的所有文件
    #print(all_files)
    if os.path.exists(back_file):
        os.removedirs(back_file)
    os.mkdir(back_file)
    for file in all_files: 
        if (os.path.isfile(os.path.join(dict_file, file))):    # 若是文件,则备份
            backup(os.path.join(dict_file, file), os.path.join(back_file, file))
        if (os.path.isdir(os.path.join(dict_file, file))):    # 若是目录,则递归调用
            dict_backup(os.path.join(dict_file, file), os.path.join(back_file, file))

dict_backup('ex', 'docs')
原文地址:https://www.cnblogs.com/wgbo/p/10112386.html