python批量修改文件夹中的文件内容,文件为.docx
时间: 2025-07-05 22:11:20 浏览: 8
### 使用Python批量编辑文件夹内的DOCX文档内容
为了实现这一目标,可以利用`python-docx`库来操作Word文档。下面提供一段完整的Python脚本来展示如何批量修改指定文件夹下的`.docx`文件内容。
#### 安装依赖包
首先需要安装必要的第三方库,可以通过pip命令完成:
```bash
pip install python-docx
```
#### 批量替换文本函数定义
创建一个用于执行单个文档中字符串查找与替换的功能模块:
```python
from docx import Document
def replace_text_in_doc(doc_path, old_str, new_str):
"""Replace all occurrences of a string with another in the given .docx file."""
document = Document(doc_path)
for paragraph in document.paragraphs:
if old_str in paragraph.text:
paragraph.text = paragraph.text.replace(old_str, new_str)
for table in document.tables:
for row in table.rows:
for cell in row.cells:
if old_str in cell.text:
cell.text = cell.text.replace(old_str, new_str)
document.save(doc_path)
```
此部分代码遍历整个文档中的段落和表格单元格,一旦发现待替换成的目标字符串就立即进行更新[^1]。
#### 遍历文件夹并应用更改
编写逻辑以递归方式访问特定路径下的所有子目录及其内部的`.docx`文件,并调用上述方法实施批处理作业:
```python
import os
def batch_replace(folder_path, old_str, new_str):
"""Recursively traverse through folder and apply text replacement to each .docx file found."""
for root, dirs, files in os.walk(folder_path):
for name in files:
if name.endswith(".docx"):
full_file_path = os.path.join(root, name)
try:
replace_text_in_doc(full_file_path, old_str, new_str)
print(f"Processed {full_file_path}")
except Exception as e:
print(f"Failed processing {full_file_path}: ", str(e))
```
这段程序会打印出成功处理过的每一个文件名以及遇到错误时的相关信息[^4]。
#### 主程序入口
最后,在主程序里设置好要操作的根目录以及其他参数即可启动任务:
```python
if __name__ == "__main__":
FOLDER_PATH = "path/to/your/folder"
OLD_STRING = "old_string_to_be_replaced"
NEW_STRING = "new_string_for_replacement"
batch_replace(FOLDER_PATH, OLD_STRING, NEW_STRING)
```
请记得将变量`FOLDER_PATH`, `OLD_STRING`, 和 `NEW_STRING` 替换为实际使用的值。
阅读全文
相关推荐


















