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
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.")
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.
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