Opening a file

The classic way of working with files is to use the open() method. This method allows you to open a file, returning an object of the file type:

open(name[, mode[, buffering]])

The opening modes of the file can be r(read), w(write), and a(append). We can add to these the b (binary), t (text), and + (open reading and writing) modes. For example, you can add a "+" to your option, which allows read/write to be done with the same object:

>>> my_file=open("file.txt","r”)

To read a file, we have several possibilities:

  • The readlines() method that reads all the lines of the file and joins them in a sequence. This method is very useful if you want to read the entire file at once:  >>> allLines = file.readlines().
  • If we want to read the file line by line, we can use the readline() method. In this way, we can use the file object as an iterator if we want to read all the lines of a file one by one:
>>> for line in file:
>>> print line
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.230.81