码迷,mamicode.com
首页 > 编程语言 > 详细

python读写文件

时间:2018-11-22 12:25:21      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:code   print   coding   ror   strip   txt   col   ...   rip   

# 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")

 

python读写文件

标签:code   print   coding   ror   strip   txt   col   ...   rip   

原文地址:https://www.cnblogs.com/dannyyao/p/10000240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!