readlines and readline的區別

#coding=utf-8
#open a file
new = open('new.txt', 'r')
print "The name of the file:%s" % new

line = new.readlines()
print "Read line1:%s" % (line)

line = new.readlines()
print "this is 2:", line   #前面已經讀取出來了,所以這裏是空的。

new.close()

#readlines(),一次性把每行讀取出來,讀取出來的格式是字符串來的。讀取出來的很多字符串構成一個list.
#




.readline() 和 .readlines() 之間的差異是後者一次讀取整個文件,象 .read() 一樣。.readlines() 自動將文件內容分析成一個行的列表,該列表可以由 Python 的 for … in … 結構進行處理。另一方面,.readline() 每次只讀取一行,通常比 .readlines() 慢得多。僅當沒有足夠內存可以一次讀取整個文件時,才應該使用 .readline()。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章