In [ ]:
# files
# Persistant way of storing a data.
# .txt,.xls,.html
# file only does three things - read,write,append
# can i insert in between line ? - NO 
# can i insert in between words ? - NO
# if you want to do above activities like writing in between line or a word you need to switch to a editor.

In [ ]:
# modes
# r - read - in this mode you can only read.
# w - write - write into the file.
# you can write into a file. If your file is not there it gets created. If it exists it get truncated to zero.
# a - append - appending to the file.
# you can keep appending to a file. adding lines to the end of the file.
# 

# take example of a wordpad and a notepad. - encoding
# b - binary mode - will take take care of this encoding.
# rb,wb,ab

In [8]:
# opening a file
# f is a variable,we call a file handle. you can put any name to this.
# open is a function which is used for opening the file.
# it takes filename and mode as arguments.
# file.txt is the filename,since we opened the ipython or ipython notebook in same location you dont need to give the path.
# say: your file is in /tmp/file1.txt locations,so you can do the following.
# g = open('/tmp/file.txt','r')
f = open('file.txt','r')

# or
# f = open('file1.txt')  
# if you dont specify the mode, which means you are opening the file in "r" mode automatically.

In [3]:
print dir(f)


['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

In [4]:
print f.mode


r

In [5]:
print f.name


file.txt

In [7]:
# f.read
print help(f.read)


Help on built-in function read:

read(...)
    read([size]) -> read at most size bytes, returned as a string.
    
    If the size argument is negative or omitted, read until EOF is reached.
    Notice that when in non-blocking mode, less data than what was requested
    may be returned, even if no size parameter was given.

None

In [9]:
print f.read(2)


th

In [10]:
print f.read(2)


is

In [11]:
print f.read()


 is my line 1.
this is my line 2.
this is my line 3.
this is my line 4.
this is my line 5.


In [12]:
print f.read()




In [ ]:
# we did not receive anything.we reached the end of the file. the pointer is stuck at the end. so you dont get to see anything.

In [15]:
# f.tell
print help(f.tell)


Help on built-in function tell:

tell(...)
    tell() -> current file position, an integer (may be a long integer).

None

In [16]:
print f.tell()


95

In [17]:
# f.seek

In [18]:
print help(f.seek)


Help on built-in function seek:

seek(...)
    seek(offset[, whence]) -> None.  Move to new file position.
    
    Argument offset is a byte count.  Optional argument whence defaults to
    0 (offset from start of file, offset should be >= 0); other values are 1
    (move relative to current position, positive or negative), and 2 (move
    relative to end of file, usually negative, although many platforms allow
    seeking beyond the end of a file).  If the file is opened in text mode,
    only offsets returned by tell() are legal.  Use of other offsets causes
    undefined behavior.
    Note that not all file objects are seekable.

None

In [19]:
print f.seek(0)


None

In [20]:
print f.tell()


0

In [21]:
# now lets do a f.read and save into a variable called my_string

my_string = f.read()
print my_string,type(my_string)


this is my line 1.
this is my line 2.
this is my line 3.
this is my line 4.
this is my line 5.
<type 'str'>

In [22]:
# f.readline
print help(f.readline)


Help on built-in function readline:

readline(...)
    readline([size]) -> next line from the file, as a string.
    
    Retain newline.  A non-negative size argument limits the maximum
    number of bytes to return (an incomplete line may be returned then).
    Return an empty string at EOF.

None

In [23]:
print f.tell()


95

In [24]:
# bringing back the pointer to zero position
f.seek(0)

In [25]:
print f.tell()


0

In [26]:
print f.readline()


this is my line 1.


In [27]:
print f.readline()


this is my line 2.


In [28]:
print f.readline()


this is my line 3.


In [29]:
print f.readline()


this is my line 4.


In [30]:
print f.readline()


this is my line 5.


In [31]:
print f.readline()  # its not printing anything as we reached the end of the file.




In [32]:
f.readline()


Out[32]:
''

In [33]:
# f.readlines
print help(f.readlines)


Help on built-in function readlines:

readlines(...)
    readlines([size]) -> list of strings, each a line from the file.
    
    Call readline() repeatedly and return a list of the lines so read.
    The optional size argument, if given, is an approximate bound on the
    total number of bytes in the lines returned.

None

In [34]:
f.seek(0) # making sure my pointer is set to zero

In [35]:
my_lines = f.readlines()

In [36]:
print my_lines,type(my_lines)


['this is my line 1.\n', 'this is my line 2.\n', 'this is my line 3.\n', 'this is my line 4.\n', 'this is my line 5.\n'] <type 'list'>

In [37]:
# f.readinto
print help(f.readinto)


Help on built-in function readinto:

readinto(...)
    readinto() -> Undocumented.  Don't use this; it may go away.

None

In [38]:
# f.xreadlines
print help(f.xreadlines)


Help on built-in function xreadlines:

xreadlines(...)
    xreadlines() -> returns self.
    
    For backward compatibility. File objects now include the performance
    optimizations previously implemented in the xreadlines module.

None

In [39]:
# snapshot
# open,name,mode,file modes,tell,seek,read,readline,readlines,readinto,xreadlines

In [ ]:
# write

In [40]:
g = open("newfile.txt",'w')
# g is a new file handle
# opened in mode w and having the file name as newfile.txt

In [41]:
print help(g.write)


Help on built-in function write:

write(...)
    write(str) -> None.  Write string str to file.
    
    Note that due to buffering, flush() or close() may be needed before
    the file on disk reflects the data written.

None

In [42]:
# you entered over keyboard,
g.write("This is my first line.\nThis is my second line.\nThis is my third line.\nThis is my fourth line.\n")
key2gyaan@key2gyaan:~/Documents/git_repositories/tuxfux-hlp-notes/batch-56/files$ cat newfile.txt key2gyaan@key2gyaan:~/Documents/git_repositories/tuxfux-hlp-notes/batch-56/files$ cat newfile.txt

In [43]:
# after doing this i dont see any content in the file.
# the content is till int he buffer

# I/O devices
# keyboard -> I/O buffer/cache -> cpu -> I/O buffer/cache -> disk
# cpu is faster than your input/output devices

In [44]:
# g.flush or g.close
print help(g.flush)


Help on built-in function flush:

flush(...)
    flush() -> None.  Flush the internal I/O buffer.

None

In [45]:
print help(g.close)


Help on built-in function close:

close(...)
    close() -> None or (perhaps) an integer.  Close the file.
    
    Sets data attribute .closed to True.  A closed file cannot be used for
    further I/O operations.  close() may be called more than once without
    error.  Some kinds of file objects (for example, opened by popen())
    may return an exit status upon closing.

None

In [46]:
g.flush()
# this will flush the I/O buffers and dump it on the device(for our case its a disk)
# Also your file is open for further writes too.
key2gyaan@key2gyaan:~/Documents/git_repositories/tuxfux-hlp-notes/batch-56/files$ cat newfile.txt This is my first line. This is my second line. This is my third line. This is my fourth line. key2gyaan@key2gyaan:~/Documents/git_repositories/tuxfux-hlp-notes/batch-56/files$

In [48]:
# what if you close the file.
g.close()
# it closes the file and you cannot do anymore operation on top of the file.

In [49]:
print g.read()


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-49-ee6f3a95f129> in <module>()
----> 1 print g.read()

ValueError: I/O operation on closed file

In [51]:
# attritute f.closed set to True

print g.closed  # your file is set to true,as it is closed.
print f.closed # your file is set to false,as it is opened.


True
False

In [ ]: