The easiest way to read / write file contents in Python

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.

+64
python
Sep 21 '10 at 7:29
source share
9 answers

If you are open to using libraries, try installing forked-path (using easy_install or pip).

Then you can do:

 from path import path s = path(filename).bytes() 

This library is fairly new, but it's a library fork that has been floating around Python for many years and has been used very little. Since I found this library a few years ago, I very rarely use os.path or open() .

+10
Sep 22 '10 at 2:19
source share
 with open('x.py') as f: s = f.read() 

*** grins ***

+118
Sep 21 '10 at 7:45
source share

This is the same as above, but does not handle errors:

 s = open(filename, 'r').read() 
+37
Sep 21 '10 at 7:33
source share

Use pathlib .

Python 3.5 and later:

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

For lower versions of Python, use 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') 
+17
Sep 20 '16 at 9:57
source share
 contents = open(filename).read() 
+16
Sep 21 '10 at 7:33
source share

This is not Perl; You do not want to force many lines at the same level. Write a function, then calling the function takes up one line of code.

 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() 
+9
Sep 21 '10 at 9:00
source share

Slow, ugly, platform specific ... but single-line; -)

 import subprocess contents = subprocess.Popen('cat %s' % filename, shell = True, stdout = subprocess.PIPE).communicate()[0] 
+5
Sep 21 '10 at 8:29
source share

Just:

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

And do what you want with the "c" content

+1
Mar 11 '19 at 10:31
source share
 contents = open(filename) 

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

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

This makes it impossible to save the list explicitly (at least with my knowledge of Python).

-one
Sep 21 2018-10-18T00:
source share



All Articles