简介:python如何快速读写txt文件
在Python中,读写文本文件是一个常见的任务,可以通过内置的open函数来实现。以下是一些快速读写文本文件的方法:
open函数以写入模式打开文件。write方法写入数据。close方法关闭文件。示例代码:
# 写入文本文件
with open('example.txt', 'w') as file:
file.write('Hello, world!')
这里使用了with语句,它会自动处理文件的打开和关闭,即使在写入过程中发生异常也是如此。
open函数以读取模式打开文件。read方法读取数据,或者使用readline方法逐行读取。close方法关闭文件。示例代码:
# 读取文本文件
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# 或者逐行读取
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # strip()去除每行末尾的换行符
with语句是处理文件读写的首选方式,因为它可以自动关闭文件,即使发生异常也不例外。'a'。'rb'和'wb'。encoding参数指定文件的编码,例如open('example.txt', 'w', encoding='utf-8')。这些是Python中读写文本文件的基本方法,可以根据具体需求选择合适的方式。