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

前端 未结 5 1458
北海茫月
北海茫月 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 03:03

    They're all achieving the same goal of returning a list of strings but using separate approaches. f.readlines() is the most Pythonic.

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

    f here is a file-like object, which is being iterated over through list, which returns lines in the file.


    with open("file.txt", "r") as f:
        data = f.read().splitlines(True)
    

    f.read() returns a string, which you split on newlines, returning a list of strings.


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

    f.readlines() does the same as above, it reads the entire file and splits on newlines.

提交回复
热议问题