0

This is my code:

from pathlib import Path
doc_path = Path.home() / "word.docx"
doc_path.touch() 

with doc_path.open(mode="w", encoding = "utf-8") as file:
    file.write("hello")

utf-8 is the default setting of word on my computer but whenever I try to open the document after having executed the code (which attempts to write the text "hello" in word) I get an error in word. There is no issue with python syntax (as no error is raised in the python shell) but there might be an issue with the character encoding I used. Thanks in advance!

Despereaux
  • 201
  • 2
  • 10

1 Answers1

0

Because you just write hello, which is not compatible with docx file. Try using doc file or write a right docx file. If you want to write docx file, you can follow this example:

pip install docx

from docx import *
document = opendocx("document.doc")
body = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
body.append(paragraph('Appending this.'))

More info here

MHP
  • 352
  • 3
  • 8