0

I have a list, and I want to write that list to a file txt

lines=[3,5,6]

result = open("result.txt", "w")
result.writelines(lines)
result.close()

But when I run, I get the following error:

writelines() argument must be a sequence of strings

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
Erna Piantari
  • 547
  • 2
  • 11
  • 26

2 Answers2

7

The error is self-explanatory: you must pass a sequence of strings, not numbers to file.writelines(). So convert the numbers to strings, and perhaps add newlines:

lines = [3, 5, 6]
with open("result.txt", "w") as f:
    f.writelines([str(line) + "\n" for line in lines])
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • Why keep the brackets in writelines? Even though is it is important to understand that is list comprehension, it is useless in this case. – Kruupös Oct 27 '16 at 09:46
  • 2
    Max: both will work, although for small number of items list comprehensions are usually faster than generators. – Eugene Yarmash Oct 27 '16 at 09:59
1

Well, you're giving it a list of integers and it plainly told you it wants a sequence of strings.
It'd just be rude not to oblige:

result.writelines(str(line) for line in lines)
tzaman
  • 46,925
  • 11
  • 90
  • 115