代码点读机 / Python / writelines

writelines Python · 文件方法

把一个字符串列表依次写入文件,不会自动加换行。

怎么用

文件.writelines(字符串列表)

小例子

with open('a.txt', 'w', encoding='utf-8') as f:
    f.writelines(['a\n', 'b\n'])
with open('a.txt', 'r', encoding='utf-8') as f:
    print(repr(f.read()))

运行结果

'a\nb\n'

官方文档:https://docs.python.org/zh-cn/3/library/io.html#io.TextIOBase

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条