Is there a difference between : “file.readlines()”, “list(file)” and “file.read().splitlines(True)”?

前端 未结 5 1438
北海茫月
北海茫月 2021-02-20 02:03

What is the difference between :

with open(\"file.txt\", \"r\") as f:
    data = list(f)

Or :

with open(\"file.txt\", \"r\") as         


        
5条回答
  •  被撕碎了的回忆
    2021-02-20 02:53

    In the 3 cases, you're using a context manager to read a file. This file is a file object.

    File Object

    An object exposing a file-oriented API (with methods such as read() or write()). Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes, etc.). File objects are also called file-like objects or streams. The canonical way to create a file object is by using the open() function. https://docs.python.org/3/glossary.html#term-file-object

    list

    with open("file.txt", "r") as f:
        data = list(f)
    

    This works because your file object is a stream like object. converting to list works roughly like this :

    [element for element in generator until I hit stopIteration]

    readlines method

    with open("file.txt", "r") as f:
        data = f.readlines()
    

    The method readlines() reads until EOF using readline() and returns a list containing the lines.

    Difference with list :

    1. You can specify the number of elements you want to read : fileObject.readlines( sizehint )

    2. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.

    read

    When should I ever use file.read() or file.readlines()?

提交回复
热议问题