在 Python 中读/写文件内容的最简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3758147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:35:41  来源:igfitidea点击:

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

python

提问by ibz

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

在 Ruby 中,您可以使用s = File.read(filename). 我在 Python 中所知道的最短最清楚的是

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

Is there any other way to do it that makes it even shorter (preferably one line) and more readable?

有没有其他方法可以使它更短(最好是一行)和更具可读性?

Note: initially I phrased the question as "doing this in a single line of code". As pointed by S.Lott, shorter doesn't necessary mean more readable. So I rephrased my question just to make clear what I meant. I think the Ruby code is better and more readable not necessarily because it's one line versus two (though that matters as well), but also because it's a class method as opposed to an instance method, which poses no question about who closes the file, how to make sure it gets closed even if an exception is raised, etc. As pointed in the answers below, you can rely on the GC to close your file (thus making this a one-liner), but that makes the code worse even though it's shorter. Not only by being unportable, but by making it unclear.

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

采纳答案by snapshoe

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

如果您愿意使用库,请尝试安装分叉路径(使用 easy_install 或 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.pathor open()any more.

这个库是相当新的,但它是一个库的分支,这个库已经在 Python 中存在多年并且已经使用了很多。自从我多年前发现这个图书馆以来,我很少使用os.pathopen()不再使用。

回答by pyfunc

This is same as above but does not handle errors:

这与上面相同,但不处理错误:

s = open(filename, 'r').read()

回答by ars

contents = open(filename).read()

回答by Mark Tolonen

with open('x.py') as f: s = f.read()

***grins***

***咧嘴笑***

回答by eumiro

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

缓慢,丑陋,特定于平台......但单线;-)

import subprocess

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

回答by Tony Veijalainen

contents = open(filename)

This gives you generator so you must save somewhere the values though, or

这为您提供了生成器,因此您必须将值保存在某处,或者

contents = [line for line in open(filename)]

This does the saving to list explicit close is not then possible (at least with my knowledge of Python).

这使得保存到列表显式关闭是不可能的(至少以我对 Python 的了解)。

回答by Glenn Maynard

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.

这不是 Perl;您不想将多行代码强制装入一行。编写一个函数,然后调用该函数需要一行代码。

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

回答by Eyal Levin

Use pathlib.

使用路径库

Python 3.5 and above:

Python 3.5 及更高版本:

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

For lower versions of Python use pathlib2:

对于较低版本的 Python,请使用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')

回答by PYK

Simple like that:

就这么简单:

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

And do whatever you want with the content "s"

对内容“s”做任何你想做的事