用 Python 读写文件内容的最简单方法

在 Ruby 中,你可以使用 s = File.read(filename)读取文件

with open(filename) as f:
s = f.read()

有没有其他方法可以让它更短(最好是一行) ,更易读?

注意: 最初我将这个问题表述为“在一行代码中完成此操作”。正如 S.Lott 所指出的,更短并不意味着更易读。所以我重新措辞了我的问题,只是为了弄清楚我的意思。我认为 Ruby 代码更好更易读,这并不一定是因为它只有一行而不是两行(尽管这也很重要) ,而是因为它是一个类方法而不是一个实例方法,实例方法没有提出关闭文件的问题,即使引发异常,如何确保文件被关闭,等等。正如下面的答案所指出的,您可以依赖 GC 来关闭文件(从而使其成为一行程序) ,但这会使代码变得更糟,即使它更短。不仅仅是因为它不可携带,还因为它不清楚。

147160 次浏览

This is same as above but does not handle errors:

s = open(filename, 'r').read()
contents = open(filename).read()
with open('x.py') as f: s = f.read()

***grins***

Slow, ugly, platform-specific... but one-liner ;-)

import subprocess


contents = subprocess.Popen('cat %s' % filename, shell = True, stdout = subprocess.PIPE).communicate()[0]

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()

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')

Simple like that:

    f=open('myfile.txt')
s=f.read()
f.close()

And do whatever you want with the content "s"