Python
Python
FILE HANDLING
WHAT IS A FILE?
• File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
• Since, random access memory (RAM) is volatile which loses its data when
computer is turned off, we use files for future use of the data.
• When we want to read from or write to a file we need to open it first.
• When we are done, it needs to be closed, so that resources that are tied
with the file are freed.
• Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
HOW TO OPEN A FILE?
• 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.
• File handling is an important part of any web application.
• Python has several functions for creating, reading,
updating, and deleting files.
FILE HANDLING
• The key function for working with files in Python is the open() function.
• The open() function takes two parameters; filename, and mode.
• There are four different methods (modes) for opening 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
In addition you can specify 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
• To open a file for reading 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 the file exists, or else you will get an error.
OPEN A FILE ON THE SERVER
• Assume we have the following file, located in the same folder
as Python:
• demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']