开发者

Python's equivalent to Ruby's File.read method

开发者 https://www.devze.com 2023-02-12 10:25 出处:网络
I\'m trying to read the contents of a file in a 开发者_如何转开发single method call. I don\'t want to have to worry about opening the file, reading from the file, and then closing the file (3 method

I'm trying to read the contents of a file in a 开发者_如何转开发single method call.

I don't want to have to worry about opening the file, reading from the file, and then closing the file (3 method calls).

I just want the content.

In ruby, there is File.read("/path/to/file"), which returns the contents of that file and properly closes it. Is there an equivalent in Python?


You can concatenate two instructions to get the same behaviour :/. But then the file isn't properly closed.

file = open("/path/to/file","r").read()

edit: Best option as far as I know leaves you needing 2/3 you mention. Just use the with statement so you don't have to worry about closing said file.

with open("/path/to/file","r") as file:
   text = file.read()


You can use a Context Manager in Python, which is available from Python 2.5.

with open('yourfile') as f:
   contents = f.read()

It will automatically, open and close the file for you. The default mode is 'r' which stands for reading.


There is no such function included with Python. It's simple enough to define one, though.

def read_whole_file(path):
    with open(path) as f:
        return f.read()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号