5

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

2
  • 1
    list comprehensions are always surrounded by []. generator expressions are surrounded by () and can also be passed directly to functions without doubling the (()) Commented Feb 22, 2013 at 4:25
  • @gnibbler: Heard of generator expressions for the first time today. Thanks! Commented Feb 22, 2013 at 18:00

5 Answers 5

9

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))
Sign up to request clarification or add additional context in comments.

3 Comments

Almost -- I don't think that writelines actually appends a newline.
@mgilson Indeed, updated - I was searching for the docs to check.
writelines was my first impression too -- I don't know why I opted for join instead -- Maybe to keep as much of OP's original code as possible. Anyway, writelines is definitely cleaner here. +1
2
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)))

2 Comments

with open('/tmp/foo.txt','w') as f: [f.write(str(i)+' ') for i in range(0,10)]
@Arcturus -- I don't actually recommend this. List-Comprehensions are for building lists. If you're not actually going to use the list that it builds, then I think is cleaner to just use a loop.
1

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.

Comments

0

You could also try,

with open('/tmp/foo.txt','w') as f:
    [f.write(str(i)+' ') for i in range(0,10)]

with the examples of @monkut or @mgilson

Comments

0

Please try the following:

open('/tmp/foo.txt','w').writelines(f'{i}\n' for i in range(10))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.