简体   繁体   中英

python-docx how can i save docx to the specific path?

I use the sample from python-docx and after I run the code I cannot find where is the docx file can I point specific path I want to add?

from docx import Document
from docx.shared import Inches

document = Document('C:\Users\Administrator\Desktop\python test\update_test\\test.docx')

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')

document.add_paragraph(
    'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
    'first item in ordered list', style='List Number'
)

filename='test.docx'


filepath=r'C:\Users\Administrator\Desktop\python test\update_test'+filename

document.add_page_break()

document.save(filepath)
document.save('C:\\Users\\Administrator\\Desktop\\python test\\update_test\\' + 'test.docx')

What wasn't explained here is that Python does not read a filepath with single backslashes. Usually, it reads it as double backslashes or single forward slashes. Your original method does work if you do this:

filePath = 'test2.docx'
doc.save('J:/drive/testFolder/CloudExile/' + filePath)

or

doc.save('J:\\drive\\testFolder\\CloudExile\\' + filePath)

I hope that helps give more insight to anyone looking at this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM