如果有人可以给我提示,我将不胜感激。我必须通过在文件名中添加前缀(日期)来重命名一批文件,因此文件在文件夹中的排列方式是有序的:从旧到新。日期本身包含在文件中。因此,我的脚本必须打开文件,查找日期并将其用作添加文件名的“前缀”。
from datetime import datetime
import re
import os
file = open('blog_entry.txt', 'r', encoding='utf-8')
source_code = file.read()
<...>
# convert the date:
date = datetime.strptime(date_only, "%d-%b-%Y")
new_date = date.strftime('%Y_%m_%d')
new_date变量应用作“前缀”,因此新文件名应类似于“ yyyy_mm_dd blog_entry.txt”我无法解决如何使用该前缀生成“新名称”的问题,因此可以将os.rename(old_name, new_name)
命令应用于文件。申请
这是使用字符串串联来构建所需的新文件名的一种方法:
from datetime import datetime
import re
import os
file = open('blog_entry.txt', 'r', encoding='utf-8')
source_code = file.read()
# read the date from the file contents
date = datetime.strptime(date_only, "%d-%b-%Y")
new_date = date.strftime('%Y_%m_%d')
path = "/path/to/your/file/"
os.rename(path + 'blog_entry.txt', path + new_date + ' ' + 'blog_entry.txt')