首页 > 代码库 > Python文件操作
Python文件操作
读写文件
f = open("test.txt","r",encoding=‘utf-8‘)data = http://www.mamicode.com/f.read()
print(data)f = open("test.txt","w",encoding=‘utf-8‘)#写入,是通过创建新文件的方式,如果有重复的名字的文件,会清空旧的内容。f.write("呵呵哒\n")#\n是换行符
f.close()#关闭文件
追加文件
f = open("test.txt","a",encoding=‘utf-8‘)f.write("呵呵哒")f.close()
逐行读文件
# Chengf = open("test.txt","r",encoding=‘utf-8‘)print(f.readline())#读一行f.close()
f = open("test.txt","r",encoding=‘utf-8‘)for i in range(5): #读五行 print(f.readline())f.close()
另一种方式readlines
首先看一下readlines输出的内容是什么样子
它会把文件内容转化为一个列表。
接下来我们输出想要的内容
# Cheng垃圾的写法f = open("test.txt","r",encoding=‘utf-8‘)count = 0for line in f.readlines(): if count <= 9:#取出前十行 print(line.strip()) count += 1 else: exit()f.close()
注意:这么读小文件没事,读大文件需要先把文件存到内存中,会导致程序卡死。
高级写法(迭代器)#
# Chengf = open("test.txt","r",encoding=‘utf-8‘)count = 0for line in f:#因为文件指针不会往回走,所以也是逐行。 if count <= 9: print(line) count += 1 else: exit()f.close()
Python文件操作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。