0

my understanding is file.write() takes string as argument and write it as a whole into file, while file.writelines() takes list of strings as argument and write it to file. Then here is my test:

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)

surprisingly, it runs successfully and here is the result

this is first employee
this is second employee
this is thirdemployee

the result is actually the same as using file.write(). so, what's the difference between file.write() and file.writelines()? am I right on the previous understanding?

JamesWang
  • 1,175
  • 3
  • 14
  • 32
  • It works with a `str` because `iter(str)` still yields a secuence of `str` (consisting of a single character each). – mata Nov 20 '19 at 17:28

1 Answers1

3

It is exactly as you have already noticed :) file.write() writes a single line to a file, file.writelines() takes a sequence of lines, and adds them to the bottom of the file.

This way Python supports Developers in coding different ways of file handling. If you want to add a whole output to a file, like an xml, you have another case as if you would simply add a line to a .csv file for example.

Let's say, you have a txt file with already 10 Lines in it. Using .writelines() you would add them like so:

    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 )

If you have the case, you simply would like to add 10 lines to a file, using file.write, you would implement it like so:

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