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

后端 未结 9 2160
走了就别回头了
走了就别回头了 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()
    

提交回复
热议问题