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

后端 未结 9 2124
走了就别回头了
走了就别回头了 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:17

    This isn't Perl; you don't want to force-fit multiple lines worth of code onto a single line. Write a function, then calling the function takes one line of code.

    def read_file(fn):
        """
        >>> import os
        >>> fn = "/tmp/testfile.%i" % os.getpid()
        >>> open(fn, "w+").write("testing")
        >>> read_file(fn)
        'testing'
        >>> os.unlink(fn)
        >>> read_file("/nonexistant")
        Traceback (most recent call last):
            ...
        IOError: [Errno 2] No such file or directory: '/nonexistant'
        """
        with open(fn) as f:
            return f.read()
    
    if __name__ == "__main__":
        import doctest
        doctest.testmod()
    
    0 讨论(0)
  • 2020-12-01 18:19
    with open('x.py') as f: s = f.read()
    

    ***grins***

    0 讨论(0)
  • 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')
    
    0 讨论(0)
  • 2020-12-01 18:23
    contents = open(filename).read()
    
    0 讨论(0)
  • 2020-12-01 18:24

    This is same as above but does not handle errors:

    s = open(filename, 'r').read()
    
    0 讨论(0)
  • 2020-12-01 18:26

    If you're open to using libraries, try installing forked-path (with either easy_install or pip).

    Then you can do:

    from path import path
    s = path(filename).bytes()
    

    This library is fairly new, but it's a fork of a library that's been floating around Python for years and has been used quite a bit. Since I found this library years ago, I very seldom use os.path or open() any more.

    0 讨论(0)
提交回复
热议问题