【问题标题】:difference between file.write() and file.writelines() Python [duplicate]file.write() 和 file.writelines() Python 之间的区别 [重复]
【发布时间】: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


【解决方案1】:

正如您已经注意到的那样:) file.write() 将一行写入文件,file.writelines() 获取一系列行,并将它们添加到文件的底部。

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

假设您有一个 txt 文件,其中已经有 10 行。使用 .writelines() 您可以像这样添加它们:

    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 )

如果你有这种情况,你只是想在一个文件中添加 10 行,使用 file.write,你可以这样实现它:

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

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 2022-01-14
    • 2014-08-16
    • 2011-04-08
    • 2012-11-24
    • 2013-06-05
    • 2021-09-29
    • 2020-05-27
    • 2016-03-23
    相关资源
    最近更新 更多