首页 > 编程知识 正文

python可以读写word(python 读)

时间:2023-11-28 02:41:34 阅读:309675 作者:BNRI

本文目录一览:

  • 1、python如何读取word文件
  • 2、python处理word文档
  • 3、如何用python读取word
  • 4、python如何读取word文件中的文本内容并写入到新的txt文件?

python如何读取word文件

 def PrintAllParagraphs(doc):

            count=doc.Paragraphs.Count

            for i in range(count-1,-1,-1):

                pr=doc.Paragraphs[i].Range

                print pr.Text

                

 app=my.Office.Word.GetInstance()

 doc=app.Documents[0]

 PrintAllParagraphs(doc)

1.什么是域      

域应用基础

        @staticmethod

        def GetInstance():

            u'''获取Word应用程序的Application对象'''

            import win32com.client

            return win32com.client.Dispatch('Word.Application')

my.Office.Word.GetInstance的方法实现如上,是一个使用win32com操纵Word Com的接口的封装

所有Paragraph即段落对象,都是通过Paragraph.Range.Text来访问它的文字的

python处理word文档

有个库叫『Python-docx』

安装之后 python 可以读写 word 文档,就可以拼接了。

如何用python读取word

使用Python的内部方法open()读取文本文件

try:

    f=open('/file','r')

    print(f.read())

finally:

    if f:

        f.close()

如果读取word文档推荐使用第三方插件,python-docx 可以在官网上下载

使用方式

# -*- coding: cp936 -*-

import docx

document = docx.Document(文件路径)

docText = 'nn'.join([

    paragraph.text.encode('utf-8') for paragraph in document.paragraphs

])

print docText

python如何读取word文件中的文本内容并写入到新的txt文件?

from docx import Document

# 打开 word文件

f = open('随便写写行.docx', 'rb')

# 读取 word文件内容

document = Document(f)

# 打印 word 文档段落内容2进制列表

# print(document.paragraphs)

# 打开一个txt文档用来写入数据

with open('result2.txt', 'w') as fw:

  # 遍历 word 段落内容列表

  for context in document.paragraphs:

# 以换行符转换成列表

      text = context.text.split('n')

      # 按行写入,同时换行

      fw.write(f"{text[0]}n")

      # 打印看看效果

      print(text[0])

f.close()

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。