Python 文件 readline()方法
readline()方法从文件中读取一整行。字符串中会保留换行符。如果指定了size参数并且是非负数,它代表了最大的字节数,包括换行符和不完整的行。
只有在遇到EOF时才返回空字符串。
语法
以下是readline()方法的语法:
fileObject.readline( size )
参数
- size - 这是要从文件中读取的字节数。
返回值
此方法返回从文件中读取的行。
以下示例显示了readline()方法的用法。
假设’foo.txt’文件包含以下文本 –
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
示例
# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
line = fo.readline(5)
print ("Read Line: %s" % (line))
# Close opened file
fo.close()
当我们运行上面的程序时,它会产生以下结果 –
Name of the file: foo.txt
Read Line: This is 1st line
Read Line: This