简体   繁体   中英

what does the param of readlines() in python do?

I am trying to figure out the parameters of readlines() . I prepared a file 'test_file.txt' contains 3 lines.

# -1, 0 gives all the lines
f = open('test_file.txt')
f.readlines()

taking None, -1, or 0 as the param produces all the lines.

f = open('test_file.txt')
f.readlines(1)

taking 1 or 2 as the param produces the first line in test file.

what does the param of readlines() ? Is it just a indicator for True or False ?

None, 0 and any number less than 0 will give ua list containing all the lines.

when n is greater than 0, this test file may give u some inspiration.

>>> f = open('test_file.txt')
>>> f.readlines()
['L\n', 'Line2\n', 'L3\n', 'L_4\n', 'Line_5\n', 'L6']

first line contain only one character, so n>1 move you to second line or more.

>>> f = open('test_file.txt')
>>> f.readlines(1)
['L\n']
>>> f = open('test_file.txt')
>>> f.readlines(2)
['L\n', 'Line2\n']

second line contains 5 characters, so [2,7] keeps u in the sencond line

>>> f = open('test_file.txt')
>>> f.readlines(6)
['L\n', 'Line2\n']
>>> f = open('test_file.txt')
>>> f.readlines(8)
['L\n', 'Line2\n', 'L3\n']

f.readlines(sizehint)

sizehint-这是要从文件读取的字节数。

The method readlines() reads until EOF using readline() and returns a list containing the lines. The parameter is the sizehint parameter. It tells the function the number of bytes to be read from the file.

The method readline()reads one entire line from the file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM