open, write and close file in a one-liner

71 Views Asked by At

I found a sample code in pathlib reference and I wonder how can I close this opened file.

p = Path('foo')
p.open('w').write('some text')

I tried to close file.

Path('foo').open('w').write('some text').close()

It caused AttributeError: 'int' object has no attribute 'close' and I understood why it caused error with this sentence as below.

Python file method write() writes a string str to the file. There is no return value

But how can I close this.

2

There are 2 best solutions below

0
mx0 On BEST ANSWER

Use pathlib.Path.write_text function to write to file and close it in one line:

Open the file pointed to in text mode, write data to it, and close the file:

Path('foo').write_text('some text')

You can't use .close() after .write() function because .write() returns number of characters written to a file (int).

There is also a pathlib.Path.read_text function to read contents of a file and close it in one go.

2
Marcin Orlowski On

You wrongly assume that chained close() is called on file handle context. It is not. The line:

Path('foo').open('w').write('some text').close()

can be split into

a = Path('foo')
b = a.open('w')
c = b.write('some text')
c.close()

and it makes no much sense because write() returns number of bytes written, not a handle, so c is an integer and the error now should be more clear. So do not optimize prematurely when not needed:

p = Path('foo')
handle = p.open('w')
handle.write('some text')
handle.close();

BUT, this is not pythonic. You should go with with:

with Path('foo').open('w') as handle:
   handle.write('some text')

and that would handle file closing for you.