In Ruby, you can read from a file using s = File.read(filename) . The shortest and clearest thing I know in Python is
with open(filename) as f: s = f.read()
Is there any other way to do this to make it even shorter (preferably one line) and more readable?
Note: I originally formulated the question as "doing this in one line of code." As S. Lott points out, short does not necessarily mean more readable. So I rephrased my question to clarify what I had in mind. I think that Ruby code is better and easier to read, not necessarily because it is a single line against two (although this is also important), and also because it is a class method and not an instance method that does not pose a question about who closes the file, how to make it close even if an exception occurs, etc. As indicated in the answers below, you can rely on the GC to close the file (thus making it single-line), but this makes the code even worse, although it is shorter. Not only due to intolerance, but also due to ambiguity.
python
ibz Sep 21 '10 at 7:29 2010-09-21 07:29
source share