Python文件的readlines()
方法使用readline()
读取并返回一个包含行的列表直到EOF。 如果可选的sizehint
参数存在,则不读取到EOF,它读取总共大约为sizehint
大小的字符串(可能在舍入到内部缓冲区大小之后)的整行。
仅在遇到EOF时才返回空字符串。
语法
以下是readlines()
方法的语法 -
fileObject.readlines( sizehint );
参数
- sizehint − 这是要从文件读取的字节数。
返回值
- 此方法返回包含行的列表。
示例
假设’foo.txt
‘文件中包含以下行 -
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
以下示例显示了readlines()
方法的用法。
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readlines()
print ("Read Line: %s" % (line))
line = fo.readlines(2)
print ("Read Line: %s" % (line))
# Close opened file
fo.close()
执行上面代码后,将得到以下结果 -
Name of the file: foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n',
'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line\n']
Read Line: