문제

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?

도움이 되었습니까?

해결책

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)

다른 팁

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top