python读写文件

# python 文件读写,使用with避免try...finally的繁琐
# 1、读取全部内容.文件太大可能会把内存爆了, 可用file.read(<字节数>)限制读取大小
with open("test.txt", "r", encoding='utf8', errors='ignore') as file:
    print("1: ", file.read())
# 2、按行读取,适合读取配置文件
with open("test.txt", "r", encoding='utf8', errors='ignore') as file:
    for line in file.readlines():
        print("2: ", line.strip())
# 3、写入文件-覆盖旧内容
with open("test.txt", "w", encoding="utf8") as file:
    file.write("尼古拉斯.姚
")
# 4、写入文件-追加
with open("test.txt", "a", encoding="utf8") as file:
    file.write("尼古拉斯.姚
")
原文地址:https://www.cnblogs.com/dannyyao/p/10000240.html