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. |
|
'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. |
|
'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. |
|
Concepts in Practice
File modes
Assume that a file named logfile.txt exists.
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.
Concepts in Practice
Writing to files
resources.txt already exists. What would happen for each of the following snippets of code?
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.