The read() method

Now we will read a file by a program. The access mode for reading is r.

Let's take the sample of a text file containing famous quotes:

Sample file

I have saved the preceding file with the name sample1.txt.

Let's write a readfile.py program to read the earlier file: 

file_input = open("sample1.txt",'r')
all_read = file_input.read()
print all_read
file_input.close()

In the given code, first we created a file_input file object, then we called file_input.read() to read the file content. After reading, the file_input file object is closed by file_input.close().  To be sure the sample file and the code readfile.py must be in the same directory. Let's check the output:

Reading a file

The preceding code is running successfully. In order to read character from the file, you can pass the argument to the read() function, for example, read(5) would read the first five characters of the file.

Let's understand the sample code readcount1.py:

file_input = open("sample1.txt",'r')
print file_input.read(20)
print file_input.read(15)
print file_input.read(10)
file_input.close()

Let's analyze the output:

Output of code read

The second line of code reads the first 20 characters of the file, the third line reads the next 15 characters, and the fourth line reads the next 10 characters of the file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.73.207