In [ ]:
# files - peristant storage
# .txt,.xls,.html,.png
# files - read,write,append
# anything more than this - editor.
# DBs - relational or non-relational dbs.

In [3]:
# open a file.
f = open("file1.txt")
# or
f = open("file1.txt","rb")

In [4]:
print type(f)
print f


<type 'file'>
<open file 'file1.txt', mode 'rb' at 0x7fa210042030>

In [ ]:
# modes
# r - read mode - reading the contents of the file.
# w - write mode - you can write into a file.
#   - if file does not exits , it create a file.
#   - if it exits it will overwrite.
# a - append the line to the end of the file.
# r+ - read and write.
# b - binary. (rb,wb,ab)

In [5]:
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 [6]:
# f.name
print f.name


file1.txt

In [7]:
# f.mode
print f.mode


rb

In [8]:
# 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 line1.
This is my line2.
This is my line3.
This is my line4.

In [12]:
print f.read()




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


Help on built-in function tell:

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

None
71

In [15]:
# f.seek
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 [22]:
f.seek(0)

In [17]:
print f.tell()


0

In [18]:
print f.read()


This is my line1.
This is my line2.
This is my line3.
This is my line4.

In [21]:
# f.next
# file handle is a iterator by default

In [23]:
f.seek(0)

In [24]:
print f.next()


This is my line1.


In [25]:
print f.next()


This is my line2.


In [26]:
print f.next()


This is my line3.


In [27]:
print f.next()


This is my line4.

In [28]:
print f.next()


---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-28-1386fc0a282d> in <module>()
----> 1 print f.next()

StopIteration: 

In [29]:
# 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 [31]:
f.seek(0)

In [32]:
print f.readline()


This is my line1.


In [33]:
print f.readline()


This is my line2.


In [34]:
print f.readline()


This is my line3.


In [35]:
print f.readline()


This is my line4.

In [36]:
print f.readline()




In [37]:
# f.readlines

In [38]:
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 [39]:
f.seek(0)

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

In [41]:
print my_lines


['This is my line1.\n', 'This is my line2.\n', 'This is my line3.\n', 'This is my line4.']

In [ ]:
# write

In [42]:
g = open("newfile.txt","wb")

In [43]:
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 [44]:
g.write("This is line one.\n This is line two.\n This is line three \n. This is line four.\n")

In [ ]:
# input => I/O buffers => cpu => I/O buffers => output

In [46]:
# f.close and f.flush
print help(g.flush)


Help on built-in function flush:

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

None

In [47]:
g.flush()

In [49]:
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 [50]:
g.close()

In [51]:
g.write("writing a new line")


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-51-0223a80baa2c> in <module>()
----> 1 g.write("writing a new line")

ValueError: I/O operation on closed file

In [53]:
# g.closed
print g.closed
print g


True
<closed file 'newfile.txt', mode 'wb' at 0x7fa210042810>

In [54]:
print f.closed
print f


False
<open file 'file1.txt', mode 'rb' at 0x7fa210042030>

In [55]:
# conditional operations
if g.closed:
    print "the file is closed , please open it"
else:
    g.write("writing a new line")


the file is closed , please open it

In [56]:
# exceptions

try:
     g.write("writing a new line")
except ValueError:
    print "buddy pleae open the file"
else:
    print "you are able to write into the file."


buddy pleae open the file

In [ ]:
# with