Sunday, 3 June 2018

File handling

Python provide many facilities for creating and accessing files. Here we shall learn about some of the basic ones. Python achieves operating system independence by accessing files through something called a file handle.

For example the following code :

nameHandle = open('new_file' , 'w')
for i in range(2):
    name = raw_input('Enter Name :  ') 
    nameHandle.write(name + '\n ')
nameHandle.close()

opens a file 'new_file ' for writing, then it asks for two inputs which are separated by new line. After you run the code always remember to close the file.

We can now open the file for reading(using the argument 'r' instead of 'w'), and print its contents.
nameHandle = open('new_file' , 'r')
for line in namehandle:
    print line
nameHandle.close()

This  code will print the input given earlier for writing.

Now,  if we write something else to this 'new_file', our previous content will get overwrite. So to avoid such condition , we open the file for appending (denoted by 'a' ) rather than writing.
nameHandle = open('new_file' , 'a')
namehandle.write('Tanush')
namehandle.write('Kanishka')
nameHandle.close()
nameHandle = open('new_file' , 'r')
for line in namehandle:
    print line
nameHandle.close()
This  code will print the input given earlier along with the appended strings.







No comments:

Post a Comment

Loan Prediction Analysis

In this post I will share my visuals ,learning and understanding of a dataset and using various algorithms of Machine Learning to analyse i...