Python File Slurp

前端 未结 3 966
北海茫月
北海茫月 2021-01-31 15:06

Is there a one-liner to read all the lines of a file in Python, rather than the standard:

f = open(\'x.txt\')
cts = f.read()
f.close()

Seems li

3条回答
  •  轮回少年
    2021-01-31 15:26

    This will slurp the content into a single string in Python 2.61 and above:

    with open('x.txt') as x: f = x.read()
    

    And this will create a list of lines:

    with open('x.txt') as x: f = x.readlines()
    

    These approaches guarantee immediate closure of the input file right after the reading.

    Footnote:

    1. This approach can also be used in Python 2.5 using from __future__ import with_statement.

    An older approach that does not guarantee immediate closure is to use this to create a single string:

    f = open('x.txt').read()
    

    And this to create a list of lines:

    f = open('x.txt').readlines()
    

    In practice it will be immediately closed in some versions of CPython, but closed "only when the garbage collector gets around to it" in Jython, IronPython, and probably some future version of CPython.

提交回复
热议问题