Easiest way to read/write a file's content in Python

后端 未结 9 2157
走了就别回头了
走了就别回头了 2020-12-01 17:32

In Ruby you can read from a file using s = File.read(filename). The shortest and clearest I know in Python is

with open(filename) as f:
    s =          


        
9条回答
  •  臣服心动
    2020-12-01 18:22

    Use pathlib.

    Python 3.5 and above:

    from pathlib import Path
    contents = Path(file_path).read_text()
    

    For lower versions of Python use pathlib2:

    $ pip install pathlib2
    

    Then

    from pathlib2 import Path
    contents = Path(file_path).read_text()
    

    Writing is just as easy:

    Path(file_path).write_text('my text')
    

提交回复
热议问题