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.
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.
with open('x.py') as f: s = f.read()
***grins***
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With