Lets look into a program to create a file,
Here ‘fo’ is the file object used.
The name of the file created here is ‘n1’ and it is a ‘text’ file.
While creating a file, we have to specify a ‘mode‘ too.
A mode specifies the type of file created.
The new file created can be ‘read only’, ‘write only‘, ‘both read and write‘ etc.
Here I have used ‘both read and write‘ mode represented by ‘w+‘.
Look at the code snippet:
# line 1 fo.write("nikhil");
Now look at the ‘line 1’.
A new file ‘n1.txt’, with file object named as ‘fo’,
which can be used for both reading and writing, is opened using the function ‘open()’.
Now look at the following line. Here we use the ‘write’ function to enter a string, ‘nikhil‘ , here in this case.
The read and write functions must be written with the corresponding file objects, as we have done,other wise it shows an error.
Then we used the ‘seek()’ function: Now in our program we had written a ‘string’ into the file and now the file pointer will be at the end of the ‘string’ we have written.
Inorder to use the ‘read()’ function we need to bring the pointer to the beguning of the file.
For this special purpose ‘seek()’ function is used.
Now we have brought the pointer to the begining of the file using ‘seek(0,0)’. (0,0) represents the begining of the file.
Now we use the ‘read function’ to read the string stored in the file into a variable ‘m’.
After the function is executed, the string stored in the file gets copied into the variable.
Now we close the file using the function ‘close()’.
And the we use the ‘print’ function to display the final result.