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

后端 未结 4 1545
天涯浪人
天涯浪人 2020-12-01 01:39

I noticed that if I iterate over a file that I opened, it is much faster to iterate over it without \"read\"-ing it.

i.e.

l = open(\'file\',\'r\')
         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 02:27

    Hope this helps!

    https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

    When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory

    Sorry for all the edits!

    For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:

    for line in f:
        print line,
    
    This is the first line of the file.
    Second line of the file
    

提交回复
热议问题