Python文件的readline()
方法从文件中读取一行。字符串中保留一个尾随的换行字符。 如果size
参数存在且非负数,则它是包含尾随换行符的最大字节数,并且可能返回不完整的行。
仅在遇到EOF时才返回空字符串。
语法
以下是readline()
方法的语法 -
fileObject.readline( size );
参数
- size − 这是要从文件读取的字节数。
返回值
- 该方法返回从文件读取的行。
示例
假设’foo.txt
‘文件中包含以下行 -
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
以下示例显示了readline()
方法的用法。
#!/usr/bin/python3
# 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
上一篇:
Python文件对象方法
下一篇:
Python os模块方法