69pao国产精品视频-久久精品一区二区二三区-精品国产精品亚洲一本大道-99国产综合一区久久

Python File readlines() 方法

python file readlines() 方法

python file 方法python file 方法

readlines() 方法用于讀取所有行(直到結(jié)束符 eof)并返回列表,該列表可以由 python 的 for... in ... 結(jié)構(gòu)進(jìn)行處理。

如果碰到結(jié)束符 eof 則返回空字符串。

語法

readlines() 方法語法如下:

fileobject.readlines( );

參數(shù)

  • 無。

返回值

返回列表,包含所有的行。

實(shí)例

以下實(shí)例演示了 readlines() 方法的使用:

文件 codebaoku.txt 的內(nèi)容如下:

1:aalaour.cn
2:aalaour.cn
3:aalaour.cn
4:aalaour.cn
5:aalaour.cn

循環(huán)讀取文件的內(nèi)容:

 

實(shí)例

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
# 打開文件
fo = open("codebaoku.txt", "r")
print "文件名為: ", fo.name
 
for line in fo.readlines(): #依次讀取每行  
    line = line.strip() #去掉每行頭尾空白  
    print "讀取的數(shù)據(jù)為: %s" % (line)
 
# 關(guān)閉文件
fo.close()


以上實(shí)例輸出結(jié)果為:

文件名為:  codebaoku.txt
讀取的數(shù)據(jù)為: 1:aalaour.cn
讀取的數(shù)據(jù)為: 2:aalaour.cn
讀取的數(shù)據(jù)為: 3:aalaour.cn
讀取的數(shù)據(jù)為: 4:aalaour.cn
讀取的數(shù)據(jù)為: 5:aalaour.cn

python file 方法python file 方法

下一節(jié):python file seek() 方法

python 教程

相關(guān)文章