Reputation: 16075
From the doc on file.writelines()
:
Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.
However, writing single lines also works:
>>> with open("/tmp/test", "w") as f:
... f.writelines("test\n")
...
>>> with open("/tmp/test") as f:
... f.readlines()
...
['test\n']
So I'm wondering if .writelines()
can accept single strings as well as sequences of strings. Any links to python 3 documentation would be appreciated.
Upvotes: 0
Views: 190
Reputation: 5616
That's because strings in Python are iterable:
>>>> for char in 'test':
.... print(char)
....
t
e
s
t
So, this code treats your string as iterable, and appends to the file char after char. It might be less efficent than using .write()
.
Upvotes: 4