Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - List comprehension within File I/O code

Tags:

python

list

io

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 [].

like image 658
prgrmr Avatar asked Feb 22 '13 02:02

prgrmr


3 Answers

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))
like image 191
Gareth Latty Avatar answered Sep 21 '22 19:09

Gareth Latty


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.

like image 24
monkut Avatar answered Sep 24 '22 19:09

monkut


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)))
like image 35
mgilson Avatar answered Sep 23 '22 19:09

mgilson