python 保存和读取 txt 文件
python
本文字数:876 字 | 阅读时长 ≈ 3 min

python 保存和读取 txt 文件

python
本文字数:876 字 | 阅读时长 ≈ 3 min

1. txt 文件的读取

有时候 r 要替换为 rb

with open('test.txt', "r", encoding='utf-8') as f: 
    lines = f.readlines()

with open(file_path, 'r', encoding='utf-8') as file:
    for line in file:
        print(line.strip())
with open('final2.txt', "r", encoding='utf-8') as f: 
    lines = f.read()

2. txt 文件的写入

with open("a.txt", "w+") as f:
    f.write(response)

with open("a.txt", "w+") as f:
    f.writelines(response)

3. txt 的写入参数

下面是参数的一些属性,一般采用 w+ 或者 a+

4. txt 的编解码属性

有时候保存的文件加载时会出现下面的问题

TypeError: a bytes-like object is required, not 'str'

问题出在 python3.5 和 Python2.7 在套接字返回值解码上有区别:python bytes 和 str 两种类型可以通过函数 encode()decode() 相互转换

line.strip().split(",")  
line.decode().strip().split(",")  # 加一个decode即可
4月 06, 2025
3月 10, 2025
12月 31, 2024