Python has a library for reading and writing and can apply a lot of functionalities on the files. There are two types of files that can be used in reading and writing files in python. One is a text file and the other one is a binary file. In a text file normal text is written while in a binary file there is only 1 or 0 that is for understanding the machine level only.
File Access Modes:
There are a total of 6 modes of accessing the files using python. These modes define how many actions we can take on the file that we are opening. The modes are:
- Read Only: It is the mode in which a file can only be read and cannot be changed, updated, or can be appended. It is also the default mode of opening the file. It is denoted by ‘r’.
- Read and write only: In this mode, files can be read as well as written or any changes can be done in the file. It is denoted by ‘r+’.
- Write only: These are the files which exist and in which python can only write in that file.
- Write and read only: In this the file is read after it is written. In this file the data is truncated or over-written in the file.
- Append Only: This opens the file for writing and the writing data will be appended in the end after the existing data.
- Append and write only: This mode is applied when a file is to be read and written. In this the data would be stored after the existing data.
Python Commands for Accessing Files:
For opening the file:
The r in the command is written such that the command does not take the characters of the name of the file as special characters.
For closing a file:
For writing a file:
For Used for inserting multiple strings at a single time:
For reading a file: