Difference in read(), readline() and readlines() in Python

后端 未结 2 563
[愿得一人]
[愿得一人] 2020-12-12 04:45

I was looking on a web of Python the commands mentioned in title and their difference; however, I have not satisfied with a complete basic understanding of these commands.

2条回答
  •  再見小時候
    2020-12-12 05:27

    For details, you should consult the library documentation, not the tutorial.

    From io documentation:

    readline(size=-1)

    Read and return one line from the stream. If size is specified, at most size bytes will be read.

    The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.


    readlines(hint=-1)

    Read and return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.

    Note that it’s already possible to iterate on file objects using for line in file: ... without calling file.readlines().

    So, readline() reads an entire line. readline(7) reads at most 7 bytes of a line. readlines() reads all the lines as a list. readlines(7) returns at most 7 lines as a list.

提交回复
热议问题