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 [ ]:
# f.softspace,f.newlines,f.errors,f.encoding

In [63]:
# 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 [62]:
# 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 [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 [57]:
# with
print g
print g.closed
with open('newfile.txt','ab') as g:
    g.write("\n writing a new line \n")
print g
print g.closed


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

In [59]:
# writelines
print help(g.writelines)


Help on built-in function writelines:

writelines(...)
    writelines(sequence_of_strings) -> None.  Write the strings to the file.
    
    Note that newlines are not added.  The sequence can be any iterable object
    producing strings. This is equivalent to calling write() for each string.

None

In [60]:
print my_lines


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

In [61]:
h = open("newfile.txt","ab")
h.writelines(my_lines)
h.flush()
# isatty tcloudost@tcloudost-VirtualBox ~ $ tty /dev/pts/2 tcloudost@tcloudost-VirtualBox ~ $

In [69]:
i = open('/dev/pts/2',"w")
i.write("\n lets go for breakfast \n")

In [71]:
print i.isatty()


True

In [72]:
i.close()

In [73]:
print h


<open file 'newfile.txt', mode 'ab' at 0x7fa210042ae0>

In [74]:
print h.isatty()


False

In [ ]:
# pickle,excel,
# json,yaml,xml

In [ ]:
# pickle

In [1]:
my_trainings = ["linux","python","django","shell"]

In [2]:
f = open("my_train.txt","wb")

In [6]:
import pickle as p
# pickling
print help(p.dump)
p.dump(my_trainings,f)
f.close()


Help on function dump in module pickle:

dump(obj, file, protocol=None)

None

In [8]:
# unpickling
print help(p.load)

g = open("my_train.txt","rb")
new_trainings = p.load(g)


Help on function load in module pickle:

load(file)

None

In [9]:
print new_trainings


['linux', 'python', 'django', 'devops']

In [ ]:
# json

In [ ]:
# installation of another module excel
tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches/batch-57/files $ ls file1.txt Learning_files.ipynb my_train.txt names.xls newfile.txt tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches/batch-57/files $ virtualenv sheets New python executable in sheets/bin/python Installing setuptools, pip...done. tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches/batch-57/files $ ls file1.txt Learning_files.ipynb my_train.txt names.xls newfile.txt sheets tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches/batch-57/files $ source sheets/bin/activate (sheets)tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches/batch-57/files $ pip freeze argparse==1.2.1 wsgiref==0.1.2 (sheets)tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches/batch-57/files $ pip install excel Downloading/unpacking excel Downloading excel-1.0.0.tar.gz Running setup.py (path:/home/tcloudost/Documents/git_repositories/python-batches/batch-57/files/sheets/build/excel/setup.py) egg_info for package excel Downloading/unpacking xlrd (from excel) Downloading xlrd-1.0.0.tar.gz (2.6MB): 2.6MB downloaded Running setup.py (path:/home/tcloudost/Documents/git_repositories/python-batches/batch-57/files/sheets/build/xlrd/setup.py) egg_info for package xlrd warning: no files found matching 'README.html' Installing collected packages: excel, xlrd Running setup.py install for excel Running setup.py install for xlrd changing mode of build/scripts-2.7/runxlrd.py from 644 to 755 warning: no files found matching 'README.html' changing mode of /home/tcloudost/Documents/git_repositories/python-batches/batch-57/files/sheets/bin/runxlrd.py to 755 Successfully installed excel xlrd Cleaning up... (sheets)tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches/batch-57/files $ pip freeze argparse==1.2.1 excel==1.0.0 wsgiref==0.1.2 xlrd==1.0.0 (sheets)tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches

In [ ]:
# xml parsing : https://www.tutorialspoint.com/python/python_xml_processing.htm