获取Python中打开的Word文件列表

问题描述 投票:0回答:1

我需要获取所有打开的 Word 文件并找到一个内容中有特殊字符串的文件。

我们打开了 3 个 word 文档:Test.docx、Test2.doc 和 blabla.doc

编辑:让我们只专注于查找所有打开的文档。

word = win32com.client.GetObject(None, 'Word.Application')
for doc in word.Documents:
    print("Next document is " + doc.name)
    

结果,它只找到一个文件,该文件是最后打开的。并且得不到其他人。输出:

> Next document is blabla.doc

> Process finished with exit code 0

那么,如何获取所有打开的文件?

python win32com
1个回答
0
投票

这对我在windows10系统上有效。它列出了 winword.exe 打开的所有文件。不仅是文档,因此必须过滤结果以获取真实文档:.doc,.docx。

l = [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if 'winword.exe'.upper() in p.info['name']]

if len(l) > 0:
  pid =l[0]['pid']
else:
  # No winword.exe found
  return []

p = psutil.Process(pid)
fileList = p.as_dict(attrs=['open_files']) # Get the list of all files opened by winword.exe. It must be filtered on doc, docx because there are many other files.
© www.soinside.com 2019 - 2024. All rights reserved.