【发布时间】:2018-05-21 09:53:47
【问题描述】:
当我在 Python2 和 Python3 中都使用 f.writelines('aaa') 时,字符串 aaa 被写入文件,但我期望的是 a 的三个单独的行。
这里是writelines的文档:
writelines(sequence_of_strings) -> None. Write the strings to the file.
Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
请注意它接受任何可迭代且str 是可迭代的,那么为什么writelines() 不为字符串中的每个项目写一行,而是只写一个字符串?
我是否需要使用f.writelines(list('aaa')) 才能获得想要的结果?
我想知道这是故意考虑还是只是一个新错误。
【问题讨论】:
-
您的分析和期望假设
writelines在给定的字符串上调用list(...),不是吗? -
虽然问题本身并不完全重复,但您可能会发现这个答案很有趣:stackoverflow.com/a/12377575/1453822
-
请注意,没有添加换行符。这能告诉你什么吗?
-
@DeepSpace 是的。
-
@DeepSpace 哦,我知道了。 3
a没有换行符只是aaa。
标签: python