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
writefunction 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') |
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.