Python Training at VMWare Pune - Day 2

Dec 13-15, 2017 Vikrant Patil

These notes are available online at http://notes.pipal.in/2017/vmware-nov-python

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

In [1]:
def rearrangemax(n):
    strnum = str(n)
    digits = sorted(strnum, reverse=True)
    return int("".join(digits))
In [2]:
rearrangemax(232343)
Out[2]:
433322
In [3]:
def rearrange(n, reverse=True):
    strnum = str(n)
    digits = sorted(strnum, reverse=reverse)
    return int("".join(digits))
In [4]:
rmax = lambda n: rearrange(n)
rmin = lambda n: rearrange(n, reverse=False)
In [5]:
rmax(232434)
Out[5]:
443322
In [6]:
rmin(2343)
Out[6]:
2334
In [9]:
def kaprekar(n, numiter):   

    while numiter>0:
        ma = rmax(n)
        mi = rmin(n)
        n = ma - mi
        numiter -= 1
        
    return n
# this will fail in case number of digits get reduced during iteration
In [11]:
def kaprekar(n, numiter=100):   

    def rearrange(n, numdigits, reverse=True):
        strnum = str(n).zfill(numdigits)
        digits = sorted(strnum, reverse=reverse)
        return int("".join(digits))
    
    ndigits = len(str(n))
    rmax = lambda n: rearrange(n, ndigits)
    rmin = lambda n: rearrange(n, ndigits, reverse=False)
    
    while numiter>0:
        ma = rmax(n)
        mi = rmin(n)
        n = ma - mi
        numiter -= 1
        
    return n
In [12]:
kaprekar(2445)
Out[12]:
6174
In [13]:
kaprekar(4546)
Out[13]:
6174
In [14]:
kaprekar(343)
Out[14]:
495
In [15]:
kaprekar(657)
Out[15]:
495

List comprehensions

In [16]:
[x*x for x in range(1,11)]
Out[16]:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [17]:
[x*x*x for x in range(1,11)]
Out[17]:
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
In [18]:
[rmax(n) for n in range(11, 100, 10)]
Out[18]:
[11, 21, 31, 41, 51, 61, 71, 81, 91]
In [19]:
even = lambda x: x%2==0
[x for x in range(1,11) if even(x)]
Out[19]:
[2, 4, 6, 8, 10]
In [20]:
setence = "Some sentence for testing list comprehensions"
words = setence.split()
In [21]:
[word.rjust(10) for word in words]
Out[21]:
['      Some',
 '  sentence',
 '       for',
 '   testing',
 '      list',
 'comprehensions']
In [22]:
[word.upper() for word in words]
Out[22]:
['SOME', 'SENTENCE', 'FOR', 'TESTING', 'LIST', 'COMPREHENSIONS']
In [23]:
[word.startswith("s") for word in words]
Out[23]:
[False, True, False, False, False, False]
In [26]:
[word for word in words if word.lower().startswith("s")]
Out[26]:
['Some', 'sentence']
In [28]:
tables = [[i*j for i in range(1,11)] for j in range(1,6)]
In [29]:
tables[0]
Out[29]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [30]:
tables[1]
Out[30]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
In [31]:
tables[:]
Out[31]:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]
In [32]:
tables[0][:]
Out[32]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [35]:
[row[0] for row in tables] #0th column
Out[35]:
[1, 2, 3, 4, 5]
In [36]:
[row[1] for row in tables] #1st column
Out[36]:
[2, 4, 6, 8, 10]

problem:

  • Write a function listpy which will list all py files from given directory
  • Write a function factors which will create list all factors of given number
  • Given that prime number has only two factors self and 1, can you write a filter is_prime which can tell if given number is prime or not?
  • Using above filter function and list comprehension can you write a function to generate list of prime numbers less than given number n.
In [37]:
def listpy(path):
    files = os.listdir(path)
    return [file for file in files if file.endswith(".py")]
In [39]:
import os
listpy(os.getcwd())
Out[39]:
['mymodule1.py',
 'module.py',
 'echo.py',
 'square.py',
 'mymodule.py',
 'arguments.py',
 'module1.py']
In [41]:
def factors(n):
    return [i for i in range(1, n+1) if n%i ==0]
In [42]:
factors(10)
Out[42]:
[1, 2, 5, 10]
In [43]:
factors(5)
Out[43]:
[1, 5]
In [44]:
def is_prime(n):
    return factors(n)==[1,n]
In [45]:
def primes(n):
    return [p for p in range(1, n+1) if is_prime(p)]
In [46]:
primes(25)
Out[46]:
[2, 3, 5, 7, 11, 13, 17, 19, 23]
In [47]:
def print_primes(n):
    for i in range(1, n+1):
        for j in range(2,i):
            if i%j==0:
                break
        else:
            print(i, end=",")

Generate a unit matrix(identity matrix..diagonal elements 1 every other element is 0). of size 5

In [48]:
def element(i,j):
    if i==j: return 1
    else: return 0
    
[[element(i, j) for i in range(5)] for j in range(5)]
Out[48]:
[[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]
In [50]:
d = {True:1, False:0}
[[d[i==j] for i in range(5)] for j in range(5)]
Out[50]:
[[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]
In [51]:
sum(primes(25))
Out[51]:
100
In [52]:
sum([1]*10)
Out[52]:
10

list Iteration patterns

In [53]:
for p in primes(25):
    print(p, end=",")
2,3,5,7,11,13,17,19,23,
In [56]:
for p in reversed(primes(25)):
    print(p, end=",")
23,19,17,13,11,7,5,3,2,
In [57]:
reversed(primes(25))
Out[57]:
<list_reverseiterator at 0x7f1fd00b0710>
In [58]:
pnumbers = primes(25)
In [60]:
for index, prime in enumerate(pnumbers):
    print(index, prime)
0 2
1 3
2 5
3 7
4 11
5 13
6 17
7 19
8 23
In [61]:
first = ["Elsa", "Alisa", "Exotica", "Beauty"]
last = ["Frozen", "Hacker", "Logica", "Nurd"]
In [62]:
for f,s in zip(first, last):
    print(f, s)
Elsa Frozen
Alisa Hacker
Exotica Logica
Beauty Nurd
In [63]:
zip(first, last)
Out[63]:
<zip at 0x7f1fd00babc8>
In [64]:
numbers = [1,2,3,4,5,6]
dstrings = ["one", "two", "three", "four", "five"]
for first, second in zip(numbers, dstrings):
    print(first, second)
1 one
2 two
3 three
4 four
5 five
In [65]:
for i, p in reversed(reversed(pnumbers)):
    print(i, p)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-65-4ba1c1506d99> in <module>()
----> 1 for i, p in reversed(enumerate(pnumbers)):
      2     print(i, p)

TypeError: 'enumerate' object is not reversible
In [67]:
list(reversed(pnumbers))
Out[67]:
[23, 19, 17, 13, 11, 7, 5, 3, 2]
In [68]:
reversed(reversed(pnumbers))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-68-736676e60c96> in <module>()
----> 1 reversed(reversed(pnumbers))

TypeError: 'list_reverseiterator' object is not reversible

problem:

  • Write a function vector_add to add elements from two lists
    >>> vector_add([1,1,1,1], [1,2,3,4])
    [2,3,4,5]
  • Find sum of all multipliers of 3 or 5 and less than 100
In [69]:
sum(first)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-69-b8751ee8a637> in <module>()
----> 1 sum(first)

TypeError: 'int' object is not iterable
In [71]:
sum(last, "")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-71-a21f60e17282> in <module>()
----> 1 sum(last, "")

TypeError: sum() can't sum strings [use ''.join(seq) instead]
In [72]:
def vector_add(v1, v2):
    return [i+j for i,j in zip(v1, v2)]
In [73]:
vector_add([1,1,1,1],[1,1,1,1])
Out[73]:
[2, 2, 2, 2]
In [74]:
sum([i for i in range(1, 1000) if i%3==0 or i%5==0])
Out[74]:
233168

Fucntions revisited

In [75]:
def usual_way_polynomial(coeff, x):
    s = 0
    for i, c in enumerate(reversed(coeff)):
        s += c * x**i
    return s
In [76]:
usual_way_polynomial([1,1,1], 2)
Out[76]:
7

make a generic polynomial generator!

In [77]:
def make_polynomial(coeffs):
    
    def poly(x):
        s = 0
        for i, c in enumerate(reversed(coeffs)):
            s += c * x**i
        return s
        
    return poly
In [78]:
P2 = make_polynomial([1,1,1])
In [79]:
P2
Out[79]:
<function __main__.make_polynomial.<locals>.poly>
In [80]:
P2(2)
Out[80]:
7
In [81]:
P2(3)
Out[81]:
13

Docstrings

In [82]:
%%file functions.py
"""
This is long deccription of module functions
functions module contains some functions to demonstrate
docstrings and doctest
"""

def add(x,y):
    """
    adds integers
    >>> add(0,1)
    1
    >>> add(1,-1)
    0
    """
    return x+y

def square(x):
    """
    calculates square of a number
    >>> square(-1)
    1
    >>> square(0)
    0
    """
    return x*x
Writing functions.py
In [83]:
import functions
In [84]:
help(functions)
Help on module functions:

NAME
    functions

DESCRIPTION
    This is long deccription of module functions
    functions module contains some functions to demonstrate
    docstrings and doctest

FUNCTIONS
    add(x, y)
        adds integers
        >>> add(0,1)
        1
        >>> add(1,-1)
        0
    
    square(x)
        calculates square of a number
        >>> square(-1)
        1
        >>> square(0)
        0

FILE
    /home/vikrant/trainings/2017/vmware-nov-python/functions.py


variable number of arguments to function

In [85]:
def mysum(*args):
    print(args)
    s = 0
    for i in args:
        s += i
    return s
In [86]:
mysum(1,2)
(1, 2)
Out[86]:
3
In [87]:
mysum(1,2,3,4,5)
(1, 2, 3, 4, 5)
Out[87]:
15

Testing

In [88]:
!python -m doctest -v functions.py
Trying:
    add(0,1)
Expecting:
    1
ok
Trying:
    add(1,-1)
Expecting:
    0
ok
Trying:
    square(-1)
Expecting:
    1
ok
Trying:
    square(0)
Expecting:
    0
ok
1 items had no tests:
    functions
2 items passed all tests:
   2 tests in functions.add
   2 tests in functions.square
4 tests in 3 items.
4 passed and 0 failed.
Test passed.

Third party module pytest is very handy automated testing you can install it using

pip3 install pytest
In [91]:
from functions import add
def test_add():
    if add(1,0) == 1:
        print("success")
    
In [92]:
test_add()
success
In [94]:
%%file functions1.py
"""
This is long deccription of module functions
functions module contains some functions to demonstrate
docstrings and doctest
"""

def add(x,y):
    """
    adds integers
    >>> add(0,1)
    1
    >>> add(1,-1)
    0
    """
    return x+y

def square(x):
    """
    calculates square of a number
    >>> square(-1)
    1
    >>> square(0)
    0
    """
    return x*x

def test_add():
    assert add(1,0) == 1
    assert add(1,-1)==0
    
def test_square():
    assert square(-1) == 1
    assert square(3) == 5
    
if __name__ == "__main__":
    test_add()
    test_square()
Overwriting functions1.py
In [95]:
!python functions1.py
Traceback (most recent call last):
  File "functions1.py", line 37, in <module>
    test_square()
  File "functions1.py", line 33, in test_square
    assert square(3) == 5
AssertionError
In [96]:
!py.test functions1.py
============================= test session starts ==============================
platform linux -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: /home/vikrant/trainings/2017/vmware-nov-python, inifile:
collected 2 items 

functions1.py .F

=================================== FAILURES ===================================
_________________________________ test_square __________________________________

    def test_square():
        assert square(-1) == 1
>       assert square(3) == 5
E       assert 9 == 5
E        +  where 9 = square(3)

functions1.py:33: AssertionError
====================== 1 failed, 1 passed in 0.05 seconds ======================

string formatting

In [100]:
def squares_and_cubes():
    for i in range(11):
        print(i, i*i, i*i*i)
In [101]:
squares_and_cubes()
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
In [102]:
def squares_and_cubes():
    for i in range(11):
        print("{0:2d} {1:3d} {2:4d}".format(i, i*i, i*i*i))
In [103]:
squares_and_cubes()
 0   0    0
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
In [104]:
"Wizard of oz if {}".format("python")
Out[104]:
'Wizard of oz if python'
In [105]:
"Wizard of {} is in {}".format("python", "oz")
Out[105]:
'Wizard of python is in oz'
In [106]:
"Purpose of life is {0} , compuation in {1} says so!".format(42, "python")
Out[106]:
'Purpose of life is 42 , compuation in python says so!'
In [107]:
"Wizard of {wizardname} is in {place}".format(wizardname="python", place="oz")
Out[107]:
'Wizard of python is in oz'
In [108]:
"23".zfill(5)
Out[108]:
'00023'
In [109]:
"name".rjust(10)
Out[109]:
'      name'
In [110]:
"name".ljust(10)
Out[110]:
'name      '
In [111]:
"name".center(10)
Out[111]:
'   name   '
In [ ]:
 

problem:

  • write a function to generate pascal triangle.
  • Write a function pretty print pascal triangle.
In [112]:
def pascal(n):
    tr = [[1]]
    for i in range(1,n):
        last = tr[-1]
        pre = [0] + last
        post = last + [0]
        row = [x+y for x,y in zip(pre, post)]
        tr.append(row)
    return tr
In [113]:
pascal(3)
Out[113]:
[[1], [1, 1], [1, 2, 1]]
In [129]:
def print_pascal(triangle):
    last = triangle[-1]
    biggestnum = max(last)
    digits = len(str(biggestnum))
    
    totalspace = len(last)*digits + len(last)-1
 
    def format_row(row, digits):
        s = ""
        for i in row:
            s  = s + " {item:{digits}}".format(item=i, digits=digits)
        return s
        
    for row in triangle:
        print(format_row(row, digits).center(totalspace))
In [130]:
print_pascal(pascal(15))
                                      1                                   
                                    1    1                                
                                 1    2    1                              
                               1    3    3    1                           
                            1    4    6    4    1                         
                          1    5   10   10    5    1                      
                       1    6   15   20   15    6    1                    
                     1    7   21   35   35   21    7    1                 
                  1    8   28   56   70   56   28    8    1               
                1    9   36   84  126  126   84   36    9    1            
             1   10   45  120  210  252  210  120   45   10    1          
           1   11   55  165  330  462  462  330  165   55   11    1       
        1   12   66  220  495  792  924  792  495  220   66   12    1     
      1   13   78  286  715 1287 1716 1716 1287  715  286   78   13    1  
    1   14   91  364 1001 2002 3003 3432 3003 2002 1001  364   91   14    1

Working with files

In [131]:
%%file three.txt
one
two
three
Writing three.txt
In [132]:
fhandle = open("three.txt")
In [133]:
fhandle.read()
Out[133]:
'one\ntwo\nthree'
In [134]:
fhandle.read()
Out[134]:
''
In [135]:
fhandle.close()
In [136]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [137]:
%%file data.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Writing data.txt
In [138]:
f = open("data.txt")
In [139]:
f.readline()
Out[139]:
'The Zen of Python, by Tim Peters\n'
In [140]:
f.readline()
Out[140]:
'\n'
In [144]:
f = open("data.txt")
for line in f.readlines():
    print(line.strip())
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [145]:
for i, line in enumerate(open("data.txt")):
    print(i, line.strip())
0 The Zen of Python, by Tim Peters
1 
2 Beautiful is better than ugly.
3 Explicit is better than implicit.
4 Simple is better than complex.
5 Complex is better than complicated.
6 Flat is better than nested.
7 Sparse is better than dense.
8 Readability counts.
9 Special cases aren't special enough to break the rules.
10 Although practicality beats purity.
11 Errors should never pass silently.
12 Unless explicitly silenced.
13 In the face of ambiguity, refuse the temptation to guess.
14 There should be one-- and preferably only one --obvious way to do it.
15 Although that way may not be obvious at first unless you're Dutch.
16 Now is better than never.
17 Although never is often better than *right* now.
18 If the implementation is hard to explain, it's a bad idea.
19 If the implementation is easy to explain, it may be a good idea.
20 Namespaces are one honking great idea -- let's do more of those!
In [147]:
for line in open("data.txt"):
    print(len(line.strip().split()))
7
0
5
5
5
5
5
5
2
9
4
5
3
10
13
12
5
8
11
13
12

problem:

  • Write a python script cat.py which works like unix command cat. It prints the file on standard output.
python cat.py data.txt three.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
.
.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

one
two
three
  • Write python script head.py which works like unix command head, it prints first n lines of file on standard output.
python head.py data.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
In [152]:
%%file cat.py

import sys

def cat(files):
    for file in files:
        f = open(file)
        print(f.read())
        
def cat_(*files):
    for file in files:
        f = open(file)
        print(f.read())
        
if __name__=="__main__":
    #cat(sys.argv[1:])
    cat_(*sys.argv[1:])
Overwriting cat.py
In [153]:
!python cat.py data.txt three.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
one
two
three
In [156]:
%%file head.py
import sys

def head(file, n=3):
    for i, line in enumerate(open(file)):
        print(line.strip())
        if (i+1)==n:
            return
        
if __name__ == "__main__":
    head(sys.argv[2], int(sys.argv[1]))
Overwriting head.py
In [157]:
!python head.py 4 data.txt
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.

problem:

  • Implement unix command wc as wc.py
  • Use this to find a file with largest number of lines from given directory
  • what about file with largest word count?
In [174]:
%%file wc.py
import sys

def line_count(file):
    lines = open(file).readlines()
    return len(lines)

def word_count(file):
    words = open(file).read().split()
    return len(words)

def char_count(file):
    chars = open(file).read()
    return len(chars)
    
def test_line():
    assert line_count("three.txt") == 3

def test_word():
    assert word_count("three.txt") == 3

def test_char():
    assert char_count("three.txt") == 14
    
if __name__ == "__main__":
    f = sys.argv[1]
    print(line_count(f), word_count(f), char_count(f), f)
Overwriting wc.py
In [175]:
!py.test wc.py
============================= test session starts ==============================
platform linux -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: /home/vikrant/trainings/2017/vmware-nov-python, inifile:
collected 3 items 

wc.py ...

=========================== 3 passed in 0.01 seconds ===========================
In [176]:
!python wc.py data.txt
21 144 856 data.txt
In [185]:
import os, wc
def filewithmaxlines(path):
    files = [f for f in os.listdir(path) if os.path.isfile(f)]
    return max(files, key=wc.line_count)
In [184]:
filewithmaxlines(".")
Out[184]:
'day1.html'
In [186]:
import os, wc
def file_with_maxword_count(path):
    files = [f for f in os.listdir(path) if os.path.isfile(f)]
    return max(files, key=wc.word_count)

Writing files

In [187]:
f = open("numbers.txt", "w")
f.write("one\n")
f.write("two\n")
f.write("three\n")
f.write("four\n")
Out[187]:
5
In [188]:
f.close()
In [189]:
!python cat.py numbers.txt
one
two
three
four

In [192]:
f = open("numbers.txt", "a")
f.write("five\n")
f.write("six\n")
f.close()
In [193]:
!python cat.py numbers.txt
one
two
three
four
five
six

In [194]:
f = open("binary.bin", "wb")
f.write(b"\x45\x56")
f.close()
In [196]:
f = open("binary.bin", "rb")
f.read()
f.close()
In [197]:
f = open("binary.bin", "ab")
f.write(b"Hello as binary")
f.close()
In [198]:
f = open("binary.bin", "rb")
print(f.read())
f.close()
b'EVHello as binary'
In [200]:
b'Hello python'.decode()
Out[200]:
'Hello python'
In [201]:
f = open("regional.txt","w", encoding="utf-8")
f.write("आ आ ॐ")
f.close()
In [202]:
f = open("regional.txt", encoding="utf-8")
f.read()
Out[202]:
'आ आ ॐ'
In [203]:
data = [["A1", "B1", "C1"],
        ["A2", "B2", "C2"],
        ["A3", "B3", "C3"],
        ["A4", "B4", "C4"]
       ]
In [204]:
%%file data1.txt
A1,B1,C1
A2,B2,C2
.
.
Writing data1.txt
In [206]:
",".join(data[0])
Out[206]:
'A1,B1,C1'

problem: Write a function writecsv to write above 2 dimensional data into a csv file.

In [207]:
def writecsv(data, file):
    f = open(file, "w")
    for row in data:
        f.write(",".join(row) + "\n")
    f.close()
In [208]:
writecsv(data, "data1.csv")
In [210]:
!python cat.py data1.csv
A1,B1,C1
A2,B2,C2
A3,B3,C3
A4,B4,C4

In [ ]: