14.2: Writing to Files
- Page ID
- 117614
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)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. |
|
Assume that a file named logfile.txt exists.
To read logfile.txt, which of the following lines of code works best?
logfile = open("logfile.txt")logfile = open("logfile.txt", 'w')logfile = open("logfile.txt", 'a')
- Answer
-
a. The default mode for the
open()function is read.
Additions are to be made to logfile.txt. Which of the following lines of code works best?
infile = open("logfile.txt")infile = open("logfile.txt", 'w')infile = open("logfile.txt", 'a')
- Answer
-
c.
'a'indicates append mode allowing additions to the file.
A new file called newlog.txt must be created. Which of the following lines of code works best?
logfile = open("newlog.txt")logfile = open("newlog.txt", 'w')logfile = open("newlog.txt", 'a')
- Answer
-
b.
'w'indicates write mode, and newlog.txt will be created or overwritten (if newlog.txt already exists) and will allow writing.
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.
"""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.
resources.txt already exists. What would happen for each of the following snippets of code?
outfile = open("resources.txt", 'w')
outfile.write("new content")
- 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.
- Answer
-
c. resources.txt is likely empty, but the state of resources.txt is uncertain. To ensure the contents are saved correctly, the
close()function must be used.
outfile = open("resources.txt", 'w')
outfile.write("new content")
outfile.close()
- The content of the resources.txt file is overwritten with the line
"new content". - The line
"new content"is added to the end of resources.txt.
- Answer
-
a. Write mode will overwrite the existing file. The
close()statement finalizes changes to the file.
outfile = open("resources.txt", 'a')
outfile.write("new content")
outfile.close()
- The content of the resources.txt file is overwritten with the line
"new content". - The line
"new content"is added to the end of resources.txt.
- Answer
-
b. Append mode adds to the existing file. resources.txt is opened such that additions can be made to the 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.
Interactive Code
- out.log
-
Hello this file should be overwritten. - Answer
-
# Open the file in write mode
outfile = open("out.txt", 'w')# Write to the new file.
outfile.write("Creating new content in a new file.")# Close the file to record changes to the file
outfile.close()
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.
Interactive Code
- out.log
-
This file should be added to...
# Open the file in append mode
outfile = open("out.log", 'a')# Write 2 lines to the file
outfile.write("\nThis is the first line.")
outfile.write("\nThis is the second line.")# Always remember to close the file to ensure changes are recorded.
outfile.close()


