Python File readline() Method
Overview
readline()This method is used to read a whole line from a file, including the "\n" character. If a non-negative parameter is specified, it returns bytes of the specified size, including the "\n" character.
Syntax
The syntax of the readline() method is as follows:
fileObject.readline(size)
Parameters
-
size-- Number of bytes to read from the file.
Return Value
Returns the bytes read from the string.
Example
The following example demonstrates the use of the readline() method:
The contents of the file example.txt are as follows:
1:www.example.com 2:www.example.com 3:www.example.com 4:www.example.com 5:www.example.com
Loop through the file contents:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开文件
fo = open("example.txt", "rw+")
print "文件名为: ", fo.name
line = fo.readline()
print "读取第一行 %s" % (line)
line = fo.readline(5)
print "读取的字符串为: %s" % (line)
# 关闭文件
fo.close()
The output of the above example is:
文件名为: example.txt 读取第一行 1:www.example.com 读取的字符串为: 2:wwwOther Extensions
Python File Methods