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

前端 未结 5 1443
北海茫月
北海茫月 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条回答
  •  旧时难觅i
    2021-02-20 02:50

    Explicit is better than implicit, so I prefer:

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

    But, when it is possible, the most pythonic is to use the file iterator directly, without loading all the content to memory, e.g.:

    with open("file.txt", "r") as f:
        for line in f:
           my_function(line)
    

提交回复
热议问题