Read and write files
Open () Returns a file object with the following basic syntax format:
Open ('filename', mode)
- The Filename:filename variable is a string value that contains the name of the file you want to access.
- Mode:mode determines the mode of opening the file: read-only, write, append, etc. All the desirable values are shown in the full list below. This parameter is non-mandatory and the default file access mode is read-only (R).
Full list of open files in different modes:
| Mode |
Describe |
| R |
Open the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode. |
| Rb |
Opens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. |
| r+ |
Open a file for read-write. The file pointer will be placed at the beginning of the file. |
| rb+ |
Opens a file in binary format for read-write. The file pointer will be placed at the beginning of the file. |
| W |
Open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. |
| Wb |
Open a file in binary format only for writing. Overwrite the file if it already exists. If the file does not exist, create a new file |
| w+ |
Open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file. |
| wb+ |
Opens a file in binary format for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file. |
| A |
Opens a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to. |
| Ab |
Opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to. |
| A + |
Open a file for read-write. If the file already exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write. |
| ab+ |
Opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to read and write. |
The following instance writes a string to NewFile:
#!/usr/bin/env python#_*_ coding:utf-8 _*_#Author:enzhi.wang#W Write modef = open ('NewFile','W', encoding='Utf-8')#file handleF.write ('I love Beijing Tian ' an gate \ n')#\n for line breaksF.write ('The sun rises on Tiananmen Square')
The result of the above example is:
Python-based file operations