Lets look into a program to create a file,

write some strings into it and also to read the string stored in it and to print it. file1 Inorder to create a file, we need to name a file object first.

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:

 fo=open("n1.txt","w+"); 
# line 1 fo.write("nikhil");
fo.seek(0,0) m=fo.read();
fo.close() print(m)

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.

The file operations in python is very much similar to c++ and its very easy to learn.   file2

Advertisements