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
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
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])
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)