word文件
(1)读word文件

import win32com
import win32com.client

def readWordFile(path):
# 调用系统word功能,可以处理doc和docx两种文件
mw = win32com.client.Dispatch("Word.Application")
# 打开文件
doc = mw.Documents.Open(path)
for paragraph in doc.Paragraphs:
line = paragraph.Range.Text
print(line)
doc.Close()
mw.Quit()

path = r"E:\\Python\\py17\\Keyboardtext\\001.docx"
readWordFile(path)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(2)读取doc并写入word

import win32com
import win32com.client

def readWordFiletootherFile(path, topath):
mw = win32com.client.Dispatch("Word.Application")
doc = mw.Documents.Open(path)
# 将word的数据保存在另一个文件
doc.SaveAs(topath, 2)
doc.Close()
mw.Quit()

path = r"E:\\Python\\py17\\Keyboardtext\\001.docx"
topath = r"E:\\Python\\py17\\Keyboardtext\\a.txt"

readWordFiletootherFile(path, topath)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(3)创建word文件

import win32com
import win32com.client
import os

def makeWordFile(path, name):
word = win32com.client.Dispatch("Word.Application")
# 让文档可见
word.Visible = True
# 创建文档
doc = word.Documents.Add()
# 写内容从头开始写
r = doc.Range(0, 0)
r.InsertAfter("你好," + name + "\n")
r.InsertAfter("python\n")
# 存储文件
doc.SaveAs(path)
doc.Close()
word.Quit()

names = ["张三", "李四", "王五"]
for name in names:
path = os.path.join(os.getcwd(http://www.amjmh.com/v/), name)
makeWordFile(path, name)
---------------------

05-23 05:31