pythonpathlib

open, write and close file in a one-liner


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.


Solution

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