Python File I/O: Read and Write Files

Python IO

Basically a programmer takes input from the console screen and writes back to the console. If the data is very large, it is not possible to show output in the console. At that time file is used to store and retrieve data. File handling is an important part of any programming language to store data permanently and retrieve data as per requirement. Files are used in Python in two modes, one is text and another one is binary. Each line of a text or binary format is ended with a special character.

There are 3 ways to perform file I/O operation.

1. First, open a file using open() and have to pass two arguments, one is a file name and another one is access mode.

    open() is used to open a file and passing arguments

File f = open (file-name, access-mode)

2. Perform read and write operations on that file. 

   read() is used for a read operation:    

r =f.read()

    write() is used for write operation:       

f.write("Sample text")

3. Close all operations of the file using close(). There is no need to pass any argument. 

    close() is used to close all operation of the file:           

f.close()

Access Modes:

There are different types of access modes are used to perform read or write operations. A list of modes is given below:

S.No Mode Description
1 This mode is used to open the file in read-only mode.
2 rb This mode is used in binary format only to open a file in read-only mode.
3 r+ Using this mode a file can perform both read and write operations.
4 rb+ Using this mode a file can do both read and write operation in binary format.
5 w It is used to open a file in write-only mode.
6 wb It is used to perform the write operations in binary format.
7 w+ Using this mode a file can perform both read and write operations.
8 wb+ Using this mode a file can do both read and write operation in binary format.
9 a It is used to open a file in append mode.
10 ab It is used to perform operations in binary format to append.
11 a+ Using this mode a file can perform read and append operation
12 ab+ Using this mode a file can perform read and append operation in binary format

Python Import:

In Python, the import is a keyword which is used to include a set of function in the program application. There are different ways to import modules in the application.

1. The first way is to import the module name at the top of the program. In this process, __import__() function is internally called in the local scope. This function returns some value which is used to get the output correctly.

Syntax:

import module_name

2. The second way is declaring the member name of the module name. In this case, __import__() function returns the value of member name.

Syntax:

import module_name.member_name

3. The third way is to import all the functions and constants from the module.

Syntax:

from module_name import *