Skip to content

Open New Created File Problem (solved) #1487

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
dp-006 opened this issue May 5, 2025 · 1 comment
Closed

Open New Created File Problem (solved) #1487

dp-006 opened this issue May 5, 2025 · 1 comment

Comments

@dp-006
Copy link

dp-006 commented May 5, 2025

I just wanted to share something interesting:

When you create a new Microsoft Word document (without opening or editing it), and try to load it using python-docx with the following code:

from docx import Document

f = open('New Microsoft Word Document.docx', 'rb')
document = Document(f)
f.close()

You’ll get this error:

<_io.BufferedReader name='New Microsoft Word Document.docx'>
Traceback (most recent call last):
  ...
zipfile.BadZipFile: File is not a zip file

This happens because a brand-new Word document that hasn't been opened or edited yet isn't actually a valid .docx file—it’s just a placeholder and not a proper ZIP archive (which .docx files are under the hood). So python-docx can’t read it and throws a BadZipFile error.


Regards...

@scanny
Copy link
Contributor

scanny commented May 5, 2025

@dp-006 You can't create a DOCX file from scratch with python-docx. All you can do is open an existing DOCX and edit it.

When you say document = Document(), that's loading a "default-template.docx" file that's included with the package. Otherwise what you give to Document needs to be a valid path (or file-like object) that is already a DOCX file.

This code is how you do what I think you're trying to do in the code above:

document = Document()
document.save("New Microsoft Word Document.docx")

@scanny scanny closed this as completed May 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants