import os
from docx import Document
import docx
# 3-it需求-数据测试方案与计划.docx
def replace_in_filenames(directory, old_str, new_str):
for filenames in os.listdir(directory):
# filename=path+filename
filename = os.path.join(path, filenames) # 连接当前目录及文件或文件夹名称
# print(filename)
if old_str in filenames:
new_filename = filenames.replace(old_str, new_str)
os.rename(os.path.join(directory, filenames), os.path.join(directory, new_filename))
if filename.endswith('.docx'):
# 打开Word文档
print(filename)
doc = docx.Document(filename)
# print(doc)
section = doc.sections[0]
header = section.header
paragraph = header.paragraphs[0]
# paragraph.text = paragraph.text.replace('数仓任务优化', 'it需求')
# paragraph.text = '数仓任务优化测试方案与计划'
header.paragraphs[0].text = '新的页眉内容'
# # 遍历文档中的所有段落
for para in doc.paragraphs:
# 将“it需求”替换为“数仓任务优化”
para.text = para.text.replace('数仓任务优化', 'it需求')
para.text = para.text.replace('20240715', '20240722') #编写日期
para.text = para.text.replace('20240705', '20240718') #测试开始日期
para.text = para.text.replace('20240719', '20240726') #上线日期
# 遍历文档中的所有表格
for table in doc.tables:
# 遍历表格中的所有单元格
for row in table.rows:
for cell in row.cells:
# 将“it需求”替换为“数仓任务优化”
cell.text = cell.text.replace('数仓任务优化', 'it需求')
cell.text = cell.text.replace('20240715', '20240722') #编写日期
cell.text = cell.text.replace('20240705', '20240718') #测试开始日期
cell.text = cell.text.replace('20240719', '20240726') #上线日期
# 保存修改后的文档
doc.save(filename)
# 示例用法
path='D:/20240719-数仓任务优化-变更'
replace_in_filenames(path, '数仓任务优化', 'it需求');
python修改文件夹名称及文件夹下文件内容替换
于 2024-07-18 17:03:36 首次发布