在Python 3中,读取文档通常指的是读取文本文件或特定格式的文档文件,如Word文档。以下是使用Python 3读取不同类型文档的基本方法:
读取文本文件
1. 使用`open()`函数:
with open('example.txt', 'r', encoding='utf-8') as file:content = file.read()print(content)
2. 使用`with`语句和`readline()`方法逐行读取:
with open('example.txt', 'r', encoding='utf-8') as file:line = file.readline()while line:print(line.strip())line = file.readline()
3. 使用`with`语句和`readlines()`方法读取所有行:
with open('example.txt', 'r', encoding='utf-8') as file:lines = file.readlines()for line in lines:print(line.strip())

读取Word文档
1. 使用`python-docx`库读取.docx文件:
from docx import Documentdoc = Document('c:/test/example.docx')for paragraph in doc.paragraphs:print(paragraph.text)
2. 使用`win32com`库读取.doc文件(需要安装`pywin32`库):
import win32com.client as wcword = wc.Dispatch('Word.Application')doc = word.Documents.Open('c:/test/example.doc')doc.SaveAs('c:/test/example.txt', 2) 2 表示另存为文本格式
请根据您的具体需求选择合适的方法。
