liveBook · Manning

Write operation

As explained in The Quick Python Book, Fourth Edition

write is a file-object method that writes text or bytes to an open file and returns the number of units written.

The write method places one string into an open file object. The string may contain several lines, but write adds no newline automatically; include \n when the output needs one. section 13.4

Use these rules when writing text:

  • Text mode can translate \n into platform-specific line endings. Pass newline="\n", newline="\r", or newline="\r\n" to force a particular representation. section 13.4
  • Binary mode returns and processes bytes without newline translation, so the newline parameter is unnecessary. section 13.4 section 13.11
  • Use writelines for a sequence of strings, but remember that it also inserts no newlines; strings without \n are concatenated. section 13.4
  • The same write and writelines methods work on specialized standard-output and standard-error file objects. section 13.6

Writing multiple lines

myfile.write("Hello\nWorld\nHow are you?") This writes three lines because the string supplies the newline characters explicitly. A write call returns the number of characters written; for standard output, the displayed count is 30 in the shown example. section 13.4 section 13.6

myfile.write("Hello\nWorld\nHow are you?")

Inspect the compact listing showing a single write call with embedded newline characters. section 13.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains arguments, embedded newlines, line-ending translation, binary mode, and the writelines alternative.
Examples
Uses a multiline string and standard-output redirection to demonstrate visible file and character-count results.
What you can do after
Apply it via Python file objects to produce controlled text output with explicit newline and line-ending behavior.
How it connects
Connects write with file objects, writelines, standard output, standard error, binary mode, and newline handling.

Also explained in

Compare how 2 books explain write operation →

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.