Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Engineering LibreTexts

14.2: Writing to Files

( \newcommand{\kernel}{\mathrm{null}\,}\)

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.

Parameter Mode name and description Example
'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')

Table 14.1 Modes for the
open()
function.
Concepts in Practice: File modes

Assume that a file named logfile.txt exists.

1.
To read logfile.txt, which of the following lines of code works best?
  1. logfile = open("logfile.txt")
  • logfile = open("logfile.txt", 'w')
  • logfile = open("logfile.txt", 'a')
  • 2.
    Additions are to be made to logfile.txt. Which of the following lines of code works best?
    1. infile = open("logfile.txt")
    2. infile = open("logfile.txt", 'w')
    3. infile = open("logfile.txt", 'a')
    3.
    A new file called newlog.txt must be created. Which of the following lines of code works best?
    1. logfile = open("newlog.txt")
    2. logfile = open("newlog.txt", 'w')
    3. logfile = open("newlog.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.

    Example 14.2

    Writing and appending to a file

        """Operations for writing and appending to files."""
    
        # Create a new file
        opfile = open("output.txt", 'w')
    
        # Writing to the file
        opfile.write("Writing to a new file.")
    
        # To add another line the newline character must be used
        opfile.write("\nSecond line.")
    
        # Ensure changes are saved by closing the file
        opfile.close()
    
        # Read and display the contents of the file
        infile = open("output.txt")
        print("\nRead the original file:\n")
        print(infile.read())
        infile.close()
    
        # Reopen the file in append mode to add to the file
        opfile = open("output.txt", 'a')
    
        # Note the use of newline characters
        opfile.write("\nAdding to the file.")
        opfile.write("\nAdding another line.")
    
        # Ensure changes are saved by closing the file
        opfile.close()
    
        # Read and display the contents of the modified file
        infile = open("output.txt")
        print("\nRead the modified file:\n")
        print(infile.read())
        infile.close()

    The code's output is:

        Read the original file:
    
        Writing to a new file.
        Second line.
    
        Read the modified file:
    
        Writing to a new file.
        Second line.
        Adding to the file.
        Adding another line.
    Checkpoint: write() and close()
    Concepts in Practice: Writing to files

    resources.txt already exists. What would happen for each of the following snippets of code?

    4.
    outfile = open("resources.txt", 'w')
    outfile.write("new content")
    1. nothing
  • The contents of the resources.txt file is overwritten with the line "new content".
  • The resources.txt file is overwritten, but the contents of resources.txt are uncertain.
  • 5.
    outfile = open("resources.txt", 'w')
    outfile.write("new content")
    outfile.close()
    1. The content of the resources.txt file is overwritten with the line "new content".
    2. The line "new content" is added to the end of resources.txt.
    6.
    outfile = open("resources.txt", 'a')
    outfile.write("new content")
    outfile.close()
    1. The content of the resources.txt file is overwritten with the line "new content".
    2. The line "new content" is added to the end of resources.txt.
    Try It: Writing to a new file

    Write a line of text to a file called out.txt. Don't forget to use close(). out.txt should only have the line of text that you have written.

    Try It: Writing to an existing file

    Add two lines of text to the file called out.log, such that out.log has three lines after the code executes.

    Hint: Don't forget that you need a newline character.


    This page titled 14.2: Writing to Files is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.

    Support Center

    How can we help?