簡體   English   中英

使用windows用python打開word文檔

[英]Open a word document with python using windows

我試圖在windows中用python打開一個word文檔,但我對windows不熟悉。

我的代碼如下。

import docx as dc
doc = dc.Document(r'C:\Users\justin.white\Desktop\01100-Allergan-UD1314-SUMMARY OF WORK.docx')

通過另一篇文章,我了解到必須將 r 放在字符串前面才能將其轉換為原始字符串,否則它會將 \\U 解釋為轉義序列。

我得到的錯誤是

PackageNotFoundError: Package not found at 'C:\Users\justin.white\Desktop\01100-Allergan-UD1314-SUMMARY OF WORK.docx'

我不確定為什么它找不到我的文檔 01100-Allergan-UD1314-SUMMARY OF WORK.docx。 路徑是正確的,因為我直接從文件系統復制了它。

感謝任何幫助。

試試這個

import StringIO
from docx import Document


file = r'H:\myfolder\wordfile.docx'

with open(file) as f:
    source_stream = StringIO(f.read())
document = Document(source_stream)
source_stream.close()

http://python-docx.readthedocs.io/en/latest/user/documents.html

此外,關於調試文件未找到錯誤,請簡化您的目錄名稱和文件名稱。 將文件重命名為 'file' 而不是引用帶有空格等的長路徑。

如果您想在 Microsoft Word 中打開文檔,請嘗試使用os.startfile()

在您的示例中,它將是:

os.startfile(r'C:\Users\justin.white\Desktop\01100-Allergan-UD1314-SUMMARY OF WORK.docx')

這將在您的計算機上以 word 格式打開文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM