在Python中打开文本文档,你可以使用内置的`open()`函数,该函数接受两个参数:文件名和打开模式。以下是使用`open()`函数打开文本文档的基本步骤:
1. 使用`open()`函数打开文件,指定文件路径和打开模式。打开模式可以是只读('r')、写入('w')、追加('a')等。
file = open('example.txt', 'r') 打开文件进行读取
2. 读取文件内容,根据你的需求选择合适的方法:
`read()`:一次性读取文件的所有内容,返回一个字符串。
file_content = file.read()
print(file_content)
`readline()`:逐行读取文件内容,返回一个字符串列表,每行作为列表中的一个元素。
line = file.readline()
while line:
print(line)
line = file.readline()
`readlines()`:读取文件的所有行,返回一个字符串列表,每行作为列表中的一个元素。
lines = file.readlines()
for line in lines:
print(line)
3. 使用`with`语句或`contextlib`模块可以自动关闭文件,防止资源泄露。
with open('example.txt', 'r') as file:
content = file.read()
print(content)
请确保在操作完成后关闭文件,以释放系统资源。