python修改word文件(doc)頁眉頁腳

網上搜這個問題,沒有現成的答案,自己找了下,把代碼記下
注:
我這里是修改的doc格式的word,不是docx
參考網址:Header and Footer — python-docx 0.8.9 documentation
python自動化辦公:玩轉word之頁眉頁腳秘笈 - 云+社區 - 騰訊云

#coding=utf8

import os

import docx

nowpath='需要修改的文件的路徑'

topath='另存到的路徑'

os.chdir(nowpath)

for iin os.listdir('.'):

    print(i)

    if os.path.splitext(i)[1]== '.doc':

        try:

            file=docx.Document(i)

            file.sections[0].header.paragraphs[0].text= '你要修改成的頁眉'

            file.sections[0].footer.paragraphs[0].text= '你要修改成的頁腳'

            file.save(os.path.join(topath,i))

        except Exception as e:

            print(e)

            continue

遇見的錯誤:
file 'xxxx.doc' is not a Word file, content type is 'application/vnd.openxmlformats-officedocument.themeManager+xml'
不是word格式的文件不能轉

我的博客即將同步至騰訊云+社區,邀請大家一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=3125dlqjnk8wc

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容