Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

14.2 Writing to files

Learning objectives

By the end of this section you should be able to

  • Understand how to open a file for writing.
  • Explain different modes for opening a file in Python.
  • Demonstrate the use of the write function to write to a file.
  • Understand the importance of closing a file.

Opening a file for writing

A file may be opened for reading, allowing no changes, or for writing, allowing changes to occur in the file. The mode defines whether a file is opened for reading only or for writing. The default mode of the open function is reading only. A second mode parameter defines the mode.

Ex: open("output.txt", 'w') opens the output.txt file in writing mode. The following table lists common modes.

Table 14.1 Modes for the open function.
ParameterMode name and descriptionExample
'r'Read mode:
Open the specified file for reading.
If the file does not exist, an error occurs.
When no mode parameter is used, the default is to open a file in read mode.
fileobj = open("input.txt")
same as:
fileobj = open("input.txt", 'r')
'w'Write mode:
Open the specified file for writing.
If the file does not exist, then the file is created.
If the file already exists, the contents of the file are overwritten.
fileobj = open("output.txt", 'w')
'a'Append mode:
Open the specified file for appending, which means adding information to the end of the existing file.
If the file does not exist, then the file is created.
fileobj = open("log.txt", 'a')

Using write and close

The write function is used to write to an already opened file. The write function will only accept a string parameter. Other variable types must be cast to string before writing using write.

The write function does not automatically add a newline character as the print function does. A newline must be added explicitly by adding a newline ('\n') character.

The write function writes automatically to a temporary store called the file buffer. To ensure that the information is written to a file, the close function must be used. The close function finalizes changes and closes the file.

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.