Question

lst = ['hello world', 'hi I am Josh']

I want to write two files, one containing lst[0] and the other lst[1]. This way, it does not work because the file comes overwritten.

for wd in lst:
   with open('hey.txt', 'wb') as f:
      f.write(wd)

How can i fix that code?

Was it helpful?

Solution

You need to specify different file names:

lst = ['hello world', 'hi I am Josh']
index = 0

for wd in lst:
   with open('hey%s.txt' % index, 'wb') as f:
      f.write(wd)
      index += 1

This will output "hello world" in hey0.txt and "hi I'm Josh" in hey1.txt

You can event replace the:

open('hey%s.txt' % index

part with:

open('hey%s.txt' % (index if index else '')

This way you'll have "hey.txt" and "hey1.txt" (it does not append the index if it equals 0)

OTHER TIPS

You could switch the order of your loops:

with open('hey.txt', 'wb') as f:
    for wd in lst:
        f.write(wd)

Or you could switch over to "append" mode:

for wd in lst:
    with open('hey.txt', 'ab') as f:
        f.write(wd)

Or write it all in one go:

with open('hey.txt', 'wb') as f:
    f.write("\n".join(lst))

Or write to two different files:

for j, wd in enumerate(lst):
    with open('hey_%i.txt' % j, 'wb') as f:
        f.write(wd)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top