【发布时间】:2020-03-30 02:55:37
【问题描述】:
我有一个关于根据文档中的特定文本更改 .doc 或 .docx 文件名的问题。
我已经能够使用 .txt 文件建立此功能。使用以下代码:
import os
import re
pat = "ID number(\\d\\d\\d\\d\\d)" #This is for the text to be found in the file
ext = '.txt' #Type of file the python is searching for
mydir = '' #Path or directory where python is doing its magic
for arch in os.listdir(mydir):
archpath = os.path.join(mydir, arch)
with open(archpath) as f:
txt = f.read()
s = re.search(pat, txt)
if s is None:
continue
name = s.group(1)
newpath = os.path.join(mydir, name)
if not os.path.exists(newpath):
os.rename(archpath, newpath + ext)
有人对此有什么看法吗?
【问题讨论】:
-
你需要解释清楚一点。在这里,您将展示如果您在哪里解析文本文件,您将如何做?您想知道如何解析 doc 或 doc ex 并查找此正则表达式吗?
-
抱歉不够详细。我想要做的是打开一个 doc 或 docx 文件并查找某个值,它将重命名文件并保存它。
-
DOC 文件不是文本文件; just plain
open可以读取纯文本,但您需要一个 DOC 格式的解析器来执行此操作。查找python-docx模块或等效模块以读取Microsoft 的文件格式。 (我不确定它是否也可以读取旧的.doc格式。也许你需要一个单独的模块,或者黑魔法。)
标签: python rename docx file-rename doc