Python file processing modes
A file is some information or data which is stored (save) in the computer storage devices. Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object. Python language supports two types of files. First one is text file that store data in the form of text file and readable by human and computer. Second one is binary file that store binary data and readable by computer only. Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
The access_mode is an optional string that specifies the mode in which the file is opened. By default, it is set to read-only "r". In this mode, we get data in text form after reading from the file. On the other hand, binary mode returns bytes. It's preferable for accessing the non-text files like an image or the exe files.
Different modes of opening a file are
- r - open a file for reading. (default)
- w - Open a file for writing. If file already exists its data will be cleared before opening. Otherwise new file will be created
- x - open for exclusive creation, failing if the file already exists
- a - open for writing, appending to the end of the file if it exists
- b - binary mode
- t - text mode (default)
- +r - Open a file for updating (reading and writing)
A text file can be opened in any one of the above said modes by specifying the option "t" along with "r", "w", "rw", and "a", so that the preceding modes become "rt", "wt", "rwt", and "at". A binary file can be opened in any one of the above said modes by specifying the option "b" along with "r", "w", "rw", and "a" so that the preceding modes become "rb", "wb", "rwb", "ab".