Reading and Writing Files
Reading and Writing Files
Example:
Executables
Databases
Application data
Configuration files
Device driver files
FILE OPERATIONS
When the user want to do some operations in the file there is a sequence of steps that should
be followed.
Open the File
Read or Write data in the file(perform operation)
Close the File
1. OPENING A FILE
The open() method
Python has a built-in function open() to open a file. This function returns a file object
and has two arguments which are file name & opening mode. The opening modes are
reading, writing or appending.
Syntax:
file_object=open(“filename”, “mode”)
where file_object is the variable to add the object and the mode tells the interpreter which way
the file will be used.
Example
f=open(“E:/Python/text.txt”, ‘r’)
f=open(“E:/Python/text.txt”, ‘w’)
FILE OPENING MODES
1 r Read Mode: Read mode is used only to read data from the
file.
4 rb+ Open a file for read and write only mode in the binary
format.
8 wb+ Opens a file for both writing and reading in binary format.
12 ab+ Open a file for appending and read-only mode in the binary
format.
2. CLOSING A FILE
The close() Method
To close a file object we will use close() method. The file gets closed and cannot be used
again for reading and writing.
The close() method of the file object flushes any unwritten information and closes the
file object, after which no more writing can be done.