When Python opens a file,
we need to give the file mode in which the file denotes opened.
file-mode directs the type of operations like read or write or append possible in the opened file
to be specific it refers to whereby the file will be used once it does open.
File modes supported by Python addressed below
Files modes
Text file mode | Binary file mode | Name |
---|---|---|
‘r’ | ‘rb’ | read-only |
‘w’ | ‘wb’ | write-only |
‘a’ | ‘ab’ | append |
‘r+’ | ‘r+b’ or ‘rb+’ | read and write |
‘w+’ | ‘w+b’ or ‘wb+’ | write and read |
‘a+’ | ‘a+b’ or ‘ab+’ | write and read |
read-only
It also known as Default mode Our File must exist already, otherwise Python raises I/O error.
write-only
In case the file does not exist, file is created. If the file exists, Python will replace existing data by over-write in the file. So this mode should be used with caution.
append
File is in write only mode. In case the file exists, the data in the file is retrived and new data written will be added to the end. If the file does not exist, Python will create a new file.
read and write
File should exist otherwise error will be given by python. Both reading and writing operations can be done with this operation.
write and read
In case file does not exist the File is created. If file exists, file is replaced but here the past data is lost. Both reading and writing operations can take place
write and read
File is created if does not exist. In case file exists, file's existing data is retained ; new data is appended. Both reading and writing operations cancan be done here.
To create a file, we need to open that file in the mode that supports write mode
like ‘w’, or ‘a’ or “wt or ‘a+’ modes.
A file mode governs the type of operations for example read/write/append possible in the opened file as it refers to how the file will be used once it does open.
Closing files
The open file remains closed by calling the close() method of the file object. Closing the files is important.
In Python, files are by default closed at the end of the code but it is a good habit to get into the mode of closing your files explicitly.
Why? Well, the operating system may not write the data out to the file until it is closed this can boost our execution performance.
What this means is that if the program exits unexpectedly then there is a danger that our precious data may not have been written to the file!
So the pro tip here is: once you finish writing to a file, close it.
The close() function performs this task and it can be done by the following syntax form:
<fileHandle>.close()
A close() function breaks the link between the file object and the file on the disk.
After close(), no tasks can be performed on that file through the file object (or file-handle).