文件名称:读写文本数据-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2024-06-29 23:06:06
python cookbook 第3版 高清 中文完整版
5.1 读写文本数据 问题 你需要读写各种不同编码的文本数据,比如ASCII,UTF-8或UTF-16编码等。 解决方案 使用带有 rt 模式的 open() 函数读取文本文件。如下所示: # Read the entire file as a single string with open('somefile.txt', 'rt') as f: data = f.read() # Iterate over the lines of the file with open('somefile.txt', 'rt') as f: for line in f: # process line ... 类似的,为了写入一个文本文件,使用带有 wt 模式的 open() 函数, 如果之前文件内容 存在则清除并覆盖掉。如下所示: