In order to read and write into a file, we will use the open()
built-in function to open the file. The open()
function creates an file_object
object. What is an object? You will understand in Chapter 11, Class and Objects. The Syntax is given as:
file_object = open(file_name ,access_mode)
The first argument,file_name
, specifies the filename that you want to open. The second argument, access_mode
, determines in which mode the file has to be opened, that is, read, write, append, and so on.
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...