I want to replicate the functionality of the following code using a list comprehension:
with open('file.txt', 'w') as textfile:
for i in range(1, 6):
textfile.write(str(i) + '\n')
I tried the following:
with open('file.txt', 'w') as textfile:
textfile.write(str([i for i in range(1, 6)]) + '\n')
but it (understandably) prints [1, 2, 3, 4, 5]
, instead of one number on a single line.
I don't have an answer to 'Why would you want to do that?'; I just want to see if it's possible. Thanks!
EDIT: Thank you all for the replies; for some reason I was under the impression that list comprehensions are always encapsulated in []
.
One way of doing this is file.writelines()
:
with open('file.txt', 'w') as textfile:
textfile.writelines(str(i) + "\n" for i in range(1, 6))
Also, if you're writing text that will be consumable by some other application, more often than not you're writing CSV, and the csv
module makes these things easy.
(In this case you only have a single value per line, so this may not be needed.)
import csv
with open("file.txt", "wb") as out_f:
writer = csv.writer(out_f)
writer.writerows([[i] for i in range(1, 6)])
NOTE The csv
module will take care of converting int to str for you.
textfile.write('\n'.join(str(i) for i in range(1,6)))
Is almost the same thing. This will leave off a trailing newline. If you need that, you could do:
textfile.write(''.join('{}\n'.format(i) for i in range(1,6)))
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