提问者:小点点

文件之间的差异。write()和文件。writelines()Python[重复]


我的理解是文件。write()字符串作为参数,将其作为一个整体写入文件,而文件。writelines()将字符串列表作为参数,并将其写入文件。这是我的测试:

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

结果实际上与使用文件相同。write()。那么,文件之间的区别是什么呢。write()文件。writelines()?我之前的理解正确吗?


共1个答案

匿名用户

正如您已经注意到的:)file.write()将一行写入文件,file.writelines()将一行序列添加到文件底部。

这种方式Python支持开发人员编码不同的文件处理方式。如果您想将整个输出添加到一个文件中,例如xml,那么您还有另一种情况,例如您只需将一行添加到. csv文件中。

比方说,您有一个已经包含10行的txt文件。使用. wordeline(),您可以这样添加它们:

    seq = ["This is 11th line\n", "This is 12th line"]
    #Write sequence of lines at the end of the file.
    fo.seek(0, 2)
    line = fo.writelines( seq )

如果您有这种情况,只需使用file向文件中添加10行即可。写下,您可以这样实现它:

    for i in range(10):
        f.write("This is line %d\r\n" % (i+1))