Python File Slurp

前端 未结 3 975
北海茫月
北海茫月 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:18

    If you are on Python3, make sure you properly respect your file's input encoding, e.g.:

    import codecs
    with codecs.open(filename, 'r', encoding="utf8") as file:
        cts = file.read()
    

    Find the list of codec names in the Python3 codec list. (The mechanism is also advisable for Python2 whenever you expect any non-ASCII input)

提交回复
热议问题