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

Python文件操作

时间:2016-10-03 19:09:39      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

读写文件

f = open("test.txt","r",encoding=utf-8)
data = 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()

逐行读文件

# Cheng
f = 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 = 0
for line in f.readlines():
    if count <= 9:#取出前十行
        print(line.strip())
        count += 1
    else:
        exit()
f.close()

注意:这么读小文件没事,读大文件需要先把文件存到内存中,会导致程序卡死。

高级写法(迭代器)#

# Cheng
f = open("test.txt","r",encoding=utf-8)
count = 0
for line in f:#因为文件指针不会往回走,所以也是逐行。
    if count <= 9:
        print(line)
        count += 1
    else:
        exit()
f.close()

 

Python文件操作

标签:

原文地址:http://www.cnblogs.com/kerwinC/p/5929381.html

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