Basics of file handdling

File Handling
File handling is one of the important part of any of the web application.

Python has many functions for creating, reading, updating, and deleting files.

File Handling
IN Python if you want to work with the files then the key function for that is open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - It is default value. Opens a file for read only purpose, and raises an error if the file does not exist

"a" - Append - Opens a file in append mode, if the file does not exist then it creates a new file with the same name.

"w" - Write - Opens a file for write mode, if the file does not exist then it creates a new file with the same name.

"x" - Create - Creates the specified file, if the file exists, then it returns an error.


In addition you can also specify that if the file should be handled as binary or text mode.

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)


Syntax
If you want to open a file in read only mode then it is enough to specify the name of the file.

f = open("demofile.txt")


The code above is the same as:

f = open("demofile.txt", "rt")


Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure that the file exists, and if the file does not exist then you will get an error.