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
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)
In [6]:
# f.name
print f.name
In [7]:
# f.mode
print f.mode
In [8]:
# f.read
print help(f.read)
In [9]:
print f.read(2)
In [10]:
print f.read(2)
In [11]:
print f.read()
In [12]:
print f.read()
In [14]:
# f.tell
print help(f.tell)
print f.tell()
In [15]:
# f.seek
print help(f.seek)
In [22]:
f.seek(0)
In [17]:
print f.tell()
In [18]:
print f.read()
In [21]:
# f.next
# file handle is a iterator by default
In [23]:
f.seek(0)
In [24]:
print f.next()
In [25]:
print f.next()
In [26]:
print f.next()
In [27]:
print f.next()
In [28]:
print f.next()
In [29]:
# f.readline
print help(f.readline)
In [31]:
f.seek(0)
In [32]:
print f.readline()
In [33]:
print f.readline()
In [34]:
print f.readline()
In [35]:
print f.readline()
In [36]:
print f.readline()
In [37]:
# f.readlines
In [38]:
print help(f.readlines)
In [39]:
f.seek(0)
In [40]:
my_lines = f.readlines()
In [41]:
print my_lines
In [ ]:
# write
In [42]:
g = open("newfile.txt","wb")
In [43]:
print help(g.write)
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)
In [47]:
g.flush()
In [49]:
print help(g.close)
In [50]:
g.close()
In [51]:
g.write("writing a new line")
In [53]:
# g.closed
print g.closed
print g
In [54]:
print f.closed
print f
In [55]:
# conditional operations
if g.closed:
print "the file is closed , please open it"
else:
g.write("writing a new line")
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."
In [ ]:
# with