Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 = 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.

like image 994
ibz Avatar asked Sep 21 '10 07:09

ibz


People also ask

Which method is used for writing the contents to a file in Python?

Writing to Files in Python Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file. This program will create a new file named test. txt in the current directory if it does not exist.


1 Answers

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

***grins***

like image 66
Mark Tolonen Avatar answered Oct 06 '22 13:10

Mark Tolonen