File handling is an important part of any web application. Python provides the facility of working on Files. A File is an external storage on a hard disk from where data can be stored and retrieved. Python has several functions for creating, reading, updating, and deleting files.
Opening a Files
Before working with Files you have to open the File. To open a File, Python built-in function open() is used. It returns an object of File which is used with other functions. Having opened the file now you can perform read, write, etc. operations on the File.
The file_name argument is a string value that contains the name of the file that you want to access.
The mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. This is an optional parameter and the default file access mode is read (r).
if the value is set to zero (0), no buffering will occur while accessing a file, if the value is set to top one (1), line buffering will be performed while accessing a file.
List of the different modes of opening a file
|r||Opens a file for reading only. (It's a default mode.)|
|w||Opens a file for writing. (If a file doesn't exist already, then it creates a new file. Otherwise, it's truncate a file.)|
|x||Opens a file for exclusive creation. (Operation fails if a file does not exist in the location.)|
|a||Opens a file for appending at the end of the file without truncating it. (Creates a new file if it does not exist in the location.)|
|t||Opens a file in text mode. (It's a default mode.)|
|b||Opens a file in binary mode.|
|+||Opens a file for updating (reading and writing.)|
Closing a Files
Writing to a File
Reading from a File