Python – Reading a File:

In this tutorial, we will learn about how to read the date from the file in python. In Python, we will use the method called “open” to open the file and “read” method to read the contents of the file

Open Method take 2 arguments.

File name – refers to the name of the file.

Mode – refers to the mode of opening the file which may be either write mode or read mode.

Modes:

r – opens for reading the file

w – opens for writing the file

r+ – opens for both reading and writing

Read Methods:

read() – This method reads the entire data in the file. if you pass the argument as read(1), it will read the first character and return the same.

readline() – This method reads the first line in the file.

Let us work on an example:

First creating the data in a file called “techsal.csv”.

Below is the data how it looks.

designers, 100, salary, 10000

programmers, 1000, salary, 15000

Dataadmins, 10, salary, 12000

Now let us import the module called “csv”, open the file and read the data:

1

>>>importcsv

1

>>>file=open("techsal.csv","r")

1

>>>print(file.read())

Below is the output:

designers, 100, salary, 10000

programmers, 1000, salary, 15000

Dataadmins, 10, salary, 12000

Let us read the first character of the data by passing the numeric argument:

1

>>>file=open("techsal.csv","r")

1

>>>print(file.read(1))

1

d

Let us read the first line of the file by using the readline() method:

1

2

3

4

5

>>>file=open("techsal.csv","r")

>>>print(file.readline())

designers,100,salary,10000

Below is another way of writing the code to read the data:

1

>>>withopen('techsal.csv')asdata:

1

...out=data.read()

1

...

1

>>>print(out)

designers, 100, salary, 10000

programmers, 1000, salary, 15000

Dataadmins, 10, salary, 12000

Once we complete the work, we need to close the file. Otherwise, it is just waste of memory. So, below is the way to close the file. Once you close the file, you cannot read the data. To read it again, you need to open it again.