Python - file handling


File is defined as collection of related data stored in a particular area on the hard disk.
File handling is very important in programming.



  """
      created_at       : 13 Feb 2017.
      updated_at       : 13 Feb 2017.
      aim of script    : To understand the concept of file handling in Python.
      coded by         : Rishikesh Agrawani.
      Python version   : 2.7.12
  """
  

 #Interactive mode programming - #1

>> f.write("Hello") >>> f.write("Dear") >>> f.close() >>> >>> f = open("details.txt","r"); >>> f.readlines() ['HelloDear'] >>> >>> f = open("details.txt","a"); >>> f.write("\n") >>> f.write("This is a ") >>> f.write("great opportunity to play with ") >>> f.write("you") >>> f.close() >>> >>> f = open("details.txt","r"); >>> f.readlines() ['HelloDear\n', 'This is a great opportunity to play with you'] >>> >>> f.read() '' >>> f = open("details.txt","r"); >>> f.read() 'HelloDear\nThis is a great opportunity to play with you' >>> print f.read() >>> f = open("details.txt","r"); >>> print f.read() HelloDear This is a great opportunity to play with you >>>

It's very interesting when we perform read/write operations on the file. So far, we saw 4 file handling methods and these are open(), read(), write() & close(). Let's see the use of 2 new methods named tell() & seek() .

  

 #Interactive mode programming - #2

>>> f = open("details.txt","w"); >>> f.write("abcdefghijklmnopqrstuvwxyz"); >>> f.close() >>> >>> f = open("details.txt","r"); >>> f.read() 'abcdefghijklmnopqrstuvwxyz' >>> >>> f.close() >>> >>> f = open("details.txt","r+"); >>> f.seek(5,0) >>> f.write("NEW_WORD"); >>> f.read() 'nopqrstuvwxyz' >>> f.tell() 26 >>> f.seek(0,0) >>> f.read() 'abcdeNEW_WORDnopqrstuvwxyz' >>>