liveBook · Manning

Writelines

As explained in The Quick Python Book, Fourth Edition

writelines is a file-object method that writes the strings from an iterable consecutively without automatically inserting newline characters.

writelines writes a sequence of strings to a file object consecutively. Despite its name, it does not add newline characters; strings become separate lines only when they already contain newlines. section 13.4

Keep these rules in mind:

  • Pass a list of strings, such as ["first\n", "second\n"]. Each string is written unchanged in sequence. section 13.4
  • Do not expect automatic line breaks: strings without trailing newlines are effectively concatenated. section 13.4
  • Use write for one string; use writelines when handling a list returned by readlines or another sequence of strings. section 13.4
  • Text-mode newline translation can map \n to platform-specific line endings; specify open(..., newline=...) when exact treatment matters. section 13.4

Copy lines without changing their endings

Open the source with newline="" so its original line endings are returned, read the strings, then pass them directly to writelines: lines = input_file.readlines(); output.writelines(lines). Because each returned string retains its ending, the output can be identical to the input. section 13.4

Writing to standard output

sys.stdout behaves as a specialized file object, so sys.stdout.writelines(["A first line.\n", "A second line.\n"]) writes both lines. Redirecting sys.stdout to a file sends the same output there. section 13.6

input_file = open("myfile.txt", 'r', newline="")
lines = input_file.readlines()
input_file.close()
output = open("myfile2.txt", 'w')
output.writelines(lines)
output.close()

Walk through a complete read-and-copy example using readlines, newline="", and writelines. section 13.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains arguments, newline behavior, platform translation, and readlines symmetry, but stops short of implementation internals.
Examples
Demonstrates exact text-file copying and redirecting sys.stdout to write two newline-terminated strings.
What it assumes
Assumes familiarity with opening files and reading strings, while clarifying newline insertion and translation from the ground up.
What you can do after
Apply it via Python file objects to write string sequences, preserve existing line endings, and redirect output.
How it connects
Connects writelines with file objects, write, readlines, newline handling, and standard output redirection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.