Akemi

Python案例——备份文件,清理过期日志,批量重命名文件

2024/10/31

带日期备份文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import os
import shutil
from datetime import datetime

src_dir='/data/test'
dest_dir='/backup/'

# 创建原目录
if not os.path.exists(src_dir):
os.makedirs(src_dir)
# 创建一些源文件
os.makedirs(os.path.join(src_dir,'subdir1'),exist_ok=True)
os.makedirs(os.path.join(src_dir,'subdir2'),exist_ok=True)
with open(os.path.join(src_dir,'file1.txt'),'w') as f:
f.write('file1 test')
with open(os.path.join(src_dir,'file2.txt'),'w') as f:
f.write('file2 test')
with open(os.path.join(src_dir,'file3.txt'),'w') as f:
f.write('file3 test')

# 创建目的目录
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)

# 获取时间戳
timestamp=datetime.now().strftime('%Y%m%d_%H%M%S')

#创建目的目录下的备份目录
backup_dir=os.path.join(dest_dir,f'backup-{timestamp}')
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)

# 遍历原目录所有文件和子目录
for item in os.listdir(src_dir):
src_file = os.path.join(src_dir,item)
dest_file = os.path.join(backup_dir,item)
# 如果目标文件是目录,则附带文件属性复制
if os.path.isdir(src_file):
shutil.copytree(src_file,backup_dir,dirs_exist_ok=True,copy_function=shutil.copy2)
# 如果目标文件是普通目录
if os.path.isfile(src_file):
shutil.copy2(src_file,backup_dir)

print(f"备份完成,文件已复制到{dest_dir}")

清理过期文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
创建模拟过期文件
touch -t $(date -d "60 days ago" +"%m%d%H%M.%S") /var/log/test1.log
touch -t $(date -d "45 days ago" +"%m%d%H%M.%S") /var/log/test2.log
touch -t $(date -d "30 days ago" +"%m%d%H%M.%S") /var/log/test3.log
touch -t $(date -d "15 days ago" +"%m%d%H%M.%S") /var/log/test4.log
touch /var/log/test5.log

import os
import time

# 设定日志目录
log_dir = '/var/log'

# 获取当前时间,并且时间戳减去30天时间,得到30天之前的时间戳
days = 30
now=time.time()
time = now - (days * 24 * 3600)

# 遍历日志目录的所有文件
for file in os.listdir(log_dir):
# 组合成绝对路径
file_path = os.path.join(log_dir,file)
# 如果是普通文件,取得该文件的修改时间
if os.path.isfile(file_path):
file_modify_time=os.path.getatime(file_path)
# 如果小于刚刚算出的值,则判断为30天之前的文件
if file_modify_time < time:
os.remove(file_path)
print(f"旧文件{file_path}已删除")

python clean.py
旧文件/var/log/test1.log已删除
旧文件/var/log/test2.log已删除
旧文件/var/log/test3.log已删除

批量重命名文件

将一个目录中所有.txt文件重命名为.bak文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
准备txt文件
mkdir /root/test
touch /root/test/test{1..20}.txt

import os

# 定义目录路径和旧扩展名
file_dir = '/root/test/'

old_ext='.txt'
new_ext='.bak'

# 遍历目录下文件
for filename in os.listdir(file_dir):
if filename.endswith(old_ext):
# 用splitext方法取出文件名(不含扩展名)
base = os.path.splitext(filename)[0]
# 拼接成新文件名
new_name = base + new_ext
# 拼接新旧文件的路径
old_file = os.path.join(file_dir,filename)
new_file = os.path.join(file_dir,new_name)
os.rename(old_file,new_file)
print(f"{filename}已重命名为{new_name}")

CATALOG
  1. 1. 带日期备份文件
  2. 2. 清理过期文件
  3. 3. 批量重命名文件