Python File Open


File management is an integral part of any web application.

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


File Handling

The main function of file management in Python is open() source.

Open function () takes two parameters; File name, and mode.

There are four different ways (methods) to open a file:


"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

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


Additionally you can specify that the file should be treated as a binary or text mode


"t" - Text - Default value. Text mode

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



Syntax

To open the file for readable enough, specify the file name:


f = open("demofile.txt")

The code above is the same as:


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

Because the readable "r", as well as the "t" text of default values, you do not need to specify.


Note: Make sure the file exists, otherwise you will get an error.