# 示例代码:Python 自动化脚本 - 文件备份
import shutil
import os
import datetime
def backup_files(source_dir, backup_dir):
"""
复制源目录中的所有文件到备份目录,并在备份目录中创建以当前日期命名的子目录。
参数:
source_dir (str): 源文件夹路径
backup_dir (str): 备份文件夹路径
"""
# 获取当前日期,格式为 YYYY-MM-DD
current_date = datetime.datetime.now().strftime("%Y-%m-%d")
# 创建以当前日期命名的子目录
target_dir = os.path.join(backup_dir, current_date)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
# 遍历源目录中的所有文件并复制到目标目录
for filename in os.listdir(source_dir):
source_file = os.path.join(source_dir, filename)
if os.path.isfile(source_file):
shutil.copy(source_file, target_dir)
print(f"已备份文件: {filename}")
# 示例调用
source_directory = "/path/to/source"
backup_directory = "/path/to/backup"
backup_files(source_directory, backup_directory)
导入模块:
shutil 用于高级文件操作(如复制文件)。os 提供了与操作系统交互的功能(如创建目录、遍历文件等)。datetime 用于获取当前日期。函数定义:
backup_files 函数接收两个参数:source_dir(源文件夹路径)和 backup_dir(备份文件夹路径)。datetime 获取当前日期,并创建一个以当前日期命名的子目录。os.listdir 遍历源目录中的所有文件,并使用 shutil.copy 将每个文件复制到目标备份目录。示例调用:
backup_files 函数进行文件备份。上一篇:python asyncio
下一篇:字典python
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站