Python File Slurp

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

    Starting in Python 3.5, you can use the pathlib module for a more modern interface. Being Python 3, it makes a distinction between reading text and reading bytes:

    from pathlib import Path
    
    text_string = Path('x.txt').read_text()  # type: str
    
    byte_string = Path('x.txt').read_bytes()  # type: bytes
    

提交回复
热议问题