Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single-liner to write to file in Python

Tags:

python

How do I perform the below write-to-file task in an easier or one-liner way?

>>> log="/tmp/test_write.log"
>>> file = open(log, "a")
>>> file.write("x" * 10)
>>> file.write("\n")
>>> file.close()

Is there some like this (bash/shell) in Python?

log="/tmp/test_write.log"
printf "`printf 'x%0.s' {1..10}`\n" >> $log
like image 616
Marcos Avatar asked Oct 16 '25 20:10

Marcos


2 Answers

There is an easier (imo) way;

from the docs

>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

So, in a one-liner you can write;

Path("path/to/my-file.txt").write_text("My Text to write.")
like image 104
SteveJ Avatar answered Oct 18 '25 17:10

SteveJ


Since you need call write and close, the only (not completely insane) way to write just a single line is to separate the two commands by a ;, which is horrible to read.

You can write a readable two-liner with the with statement:

with open("/tmp/test_write.log", "a") as log:
    log.write("x"*10 + '\n')

Files are context managers and using the with statement ensures that the file is closed once you exit the block.

like image 34
timgeb Avatar answered Oct 18 '25 15:10

timgeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!