Python学习之 File readlines() 方法

功能描述:

    readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for... in ... 结构进行处理。

如果碰到结束符 EOF 则返回空字符串。

示例:

    语法:

       fileObject.readlines( )

    文件示例:

1:www.helloworld.com
2:www.helloworld.com
3:www.helloworld.com
4:www.helloworld.com
5:www.helloworld.com

     读取过程:

# 打开文件
fp = open("helloworld.txt", "r")
print("文件名为: ", fp.name)
for line in fp.readlines(): #依次读取每行 
line = line.strip() #去掉每行头尾空白 
print("读取数据为: %s" % (line))
# 关闭文件
fo.close()

    输出结果:

文件名为:  helloworld.txt
读取的数据为: 1:www.helloworld.com
读取的数据为: 2:www.helloworld.com
读取的数据为: 3:www.helloworld.com
读取的数据为: 4:www.helloworld.com
读取的数据为: 5:www.helloworld.com

 

你可能感兴趣的:(python)