Reading file


In [2]:
filename='LittleRedRidingHood.txt'
with open(filename) as f:
    print f.read()


All the better to hug you with, my dear.
Grandmother, what big legs you have!
All the better to run with, my child.
Grandmother, what big ears you have!
All the better to hear with, my child.
Grandmother, what big eyes you have!
All the better to see with, my child.
Grandmother, what big teeth you have got!
All the better to eat you up with.

In [3]:
filename='LittleRedRidingHood.txt'
with open(filename) as f:
    for line in f:
        print line


All the better to hug you with, my dear.

Grandmother, what big legs you have!

All the better to run with, my child.

Grandmother, what big ears you have!

All the better to hear with, my child.

Grandmother, what big eyes you have!

All the better to see with, my child.

Grandmother, what big teeth you have got!

All the better to eat you up with.

Syntax

str.split(str=" ", num=string.count(str)).

Parameters

str -- This is any delimeter, by default it is space.

num -- this is number of lines to be made

Return Value

This method returns a list of lines.

In [4]:
line


Out[4]:
'All the better to eat you up with.'

In [5]:
line.split(" ")


Out[5]:
['All', 'the', 'better', 'to', 'eat', 'you', 'up', 'with.']

Writing file


In [6]:
filename='hello.txt'
with open(filename,'w') as f:
    f.write('Hello World!');

In [7]:
ls


 Volume in drive C has no label.
 Volume Serial Number is A8BF-C894

 Directory of C:\Users\Wasit\Documents\GitHub\PythonDay\notebook\day04

06/06/2016  16:45    <DIR>          .
06/06/2016  16:45    <DIR>          ..
06/06/2016  16:10    <DIR>          .ipynb_checkpoints
06/06/2016  16:45             7,399 fileIO.ipynb
06/06/2016  16:46                12 hello.txt
06/06/2016  16:16               351 LittleRedRidingHood.txt
               3 File(s)          7,762 bytes
               3 Dir(s)  71,244,111,872 bytes free

Array to string


In [8]:
A=[5,6,7]

In [9]:
s=""
for i in A:
    s+= "{} ".format(i)

print s


5 6 7 

In [10]:
s


Out[10]:
'5 6 7 '

In [11]:
s=""
for i in A:
    s+= "%d "%(i)
print s


5 6 7 

In [12]:
B=[[1,2,3],[4,5,6],[7,8,9]]
print B


[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In [13]:
s=""
for row in B:
    for column in row:
        s+= "%d "%(column)
    s+= "\n"
print s


1 2 3 
4 5 6 
7 8 9 

Exercise1

To write the matrix b to a text file named 'B.dat'. 
Then read the text file back to a new variable called 'C' and print it out in a matrix format.

Home work: Multi-index sorting

see in the classroom


In [ ]: