# 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("尼古拉斯.姚\n")
# 4、写入文件-追加
with open("test.txt", "a", encoding="utf8") as file:
    file.write("尼古拉斯.姚\n")

 

posted on 2018-11-22 11:56  蛋尼  阅读(134)  评论(0编辑  收藏  举报