我可以使用 .writelines() 将单行写入文件吗?
Can I use .writelines() for writing a single line to a file?
来自 file.writelines()
上的文档:
Write a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings.
但是,写单行也可以:
>>> with open("/tmp/test", "w") as f:
... f.writelines("test\n")
...
>>> with open("/tmp/test") as f:
... f.readlines()
...
['test\n']
所以我想知道 .writelines()
是否可以接受单个字符串以及字符串序列。任何指向 python 3 文档的链接将不胜感激。
那是因为 Python 中的字符串是可迭代的:
>>>> for char in 'test':
.... print(char)
....
t
e
s
t
因此,此代码将您的字符串视为可迭代的,并在 char 之后追加到文件 char。它可能不如使用 .write()
.
有效
来自 file.writelines()
上的文档:
Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.
但是,写单行也可以:
>>> with open("/tmp/test", "w") as f:
... f.writelines("test\n")
...
>>> with open("/tmp/test") as f:
... f.readlines()
...
['test\n']
所以我想知道 .writelines()
是否可以接受单个字符串以及字符串序列。任何指向 python 3 文档的链接将不胜感激。
那是因为 Python 中的字符串是可迭代的:
>>>> for char in 'test':
.... print(char)
....
t
e
s
t
因此,此代码将您的字符串视为可迭代的,并在 char 之后追加到文件 char。它可能不如使用 .write()
.