【发布时间】:2019-11-20 17:15:56
【问题描述】:
我的理解是file.write()以string为参数,整体写入文件,file.writelines()以list of strings为参数,写入文件。然后这是我的测试:
file_name = "employees"
content = "this is first employee\nthis is second employee\nthis is thirdemployee\n"
def write_lines(name: str, lines: list) -> None:
with open(name, "w") as file:
file.writelines(lines)
def read(name: str) -> None:
with open(name) as file:
print(file.read())
write_lines(file_name, content)
read(file_name)
令人惊讶的是,它运行成功,结果如下
this is first employee
this is second employee
this is thirdemployee
结果实际上与使用 file.write() 相同。那么,file.write() 和 file.writelines() 有什么区别?我之前的理解是对的吗?
【问题讨论】:
-
它与
str一起工作,因为iter(str)仍然产生str的序列(每个由一个字符组成)。
标签: python