def write_file(filename):
with open(filename, "w") as f: # open the file in write mode in text mode
f.write("one") # it is expected to write text/str
f.write("two")
f.write("\n")
f.write("three")
def cat(filename):
with open(filename) as f: # pen in text mode for reading
print(f.read())Module II - Day 3
Python Foundation
Nov-Jan 2025 batch, Vikrant Patil
Date: 30 Dec 2025
Click here for All Notes
login to https://traininghub.vikrant.dev/ with your username and create a notebook with name module2-day3.ipynb
© Vikrant Patil
Writing Files
default modes - text mode, read mode
write_file("numbers.txt")cat("numbers.txt")onetwo
three
with open("test.txt", "w") as f: # it will create new file if it does not exist and it will over write if file already exists
f.write(10)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[6], line 2 1 with open("test.txt", "w") as f: # it will create new file if it does not exist and it will over write if file already exists ----> 2 f.write(10) TypeError: write() argument must be str, not int
with open("test.txt", "w") as f:
f.write(str(10))
cat("numbers.txt")onetwo
three
with open("numbers.txt", "w") as f:
f.write("four")
f.write("\n")
f.write("five")cat("numbers.txt")four
five
with open("numbers.txt", "a") as f: # append mode will write at the end of existing file
f.write("\nsix\nseven\neight")cat("numbers.txt")four
five
six
seven
eight
!ls digits*ls: cannot access 'digits*': No such file or directory
with open("digits.txt", "a") as f: # append mode will write at the end of existing file
f.write("\nsix\nseven\neight")!ls digits*digits.txt
cat("digits.txt")
six
seven
eight
Here is complete list of all modes for handling files
================ ============================================
mode meaning
================ ============================================
no mode given open file in text mode for reading
w open file to write. if file exists, overrite
a open file to append. if file exists, append
rb or b open file to read bibary
wb open file in write mode to write binary.
wa open file in bibary and append mode
================ ============================================
!cat numbers.txtfour
five
six
seven
eight
six
seven
eight
x = 10x.to_bytes()b'\n'
"text data".encode()b'text data'
if you want to convert exiting data into binary (bytes) - text use .encode - for other items use .to_bytes
with open("digits.bin", "wb") as f: # write binary mode will write at the end of existing file
data = "\nsix\nseven\neight".encode()
f.write(data)!cat digits.bin
six
seven
eight
cat("digits.bin")
six
seven
eight
string formating
template = "Hello my name is {name} and I live in {country}!"template.format(name="Vikrant", country="India")'Hello my name is Vikrant and I live in India!'
f"Hello my name is {name} and I live in {country}!"--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[29], line 1 ----> 1 f"Hello my name is {name} and I live in {country}!" NameError: name 'name' is not defined
name = "Vikrant"
country = "India"f"Hello my name is {name} and I live in {country}!"'Hello my name is Vikrant and I live in India!'
"Lets write some numbers here {},{},{},{}".format(1, 2, 3, 4)'Lets write some numbers here 1,2,3,4'
"Lets write some names here {2},{1},{3},{0}".format("vikrant", "abid", "jagdish", "pallavi")'Lets write some names here jagdish,abid,pallavi,vikrant'
for i in range(1, 10):
print(i, i**2, i**3)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
for i in range(1, 10):
print(f"{i:1d} {i**2:2d} {i**3:3d}")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
x = 3
for i in range(1, 10):
print(f"{i:1d} {i**2:2d} {i**3:{x}d}")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
problem - Write a function to generate pascal traingle in list format given the size of base - Write a function to pretty print pascal triangle print_pascal given the traingle
1
1 1
1 2 1
1 3 3 1
[[1],[1,1,]][[1], [1, 1]]
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]][[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]
1 2 1
1 2 1
-----------------
1 3 3 1
1 1 1 1 1 2 2 2 2 2
a = [1, 1, 1, 1]
b = [2, 2, 2, 2]x = []
for i in range(len(a)):
x.append(a[i] + b[i])x[3, 3, 3, 3]
r = []
for x,y in zip(a, b):
r.append(x+y)[x+y for x,y in zip(a,b)][3, 3, 3, 3]
x = ['x1','x2','x3']
y = ['y1','y2']previousline = [1, 2, 1]previousline[1:][2, 1]
[1, 2, 1]
[2, 1]def nextline(previousline):
return [x+y for x,y in zip(previousline, previousline[1:])]nextline([1, 2, 1])[3, 3]
def nextline(previousline):
return [1] + [x+y for x,y in zip(previousline, previousline[1:])] + [1]nextline([1, 2, 1])[1, 3, 3, 1]
nextline([1])[1, 1]
nextline([1, 1])[1, 2, 1]
nextline([1,2,1])[1, 3, 3, 1]
base = 5
tr = [[1]]
for i in range(1, base):
previousline = tr[-1]
currentline = nextline(previousline)
print(currentline)
tr.append(currentline)
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
tr[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
def pascal(base):
tr = [[1]]
for i in range(1, base):
previousline = tr[-1]
currentline = nextline(previousline)
tr.append(currentline)
return trpascal(5)[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
pascal(2)[[1], [1, 1]]
pascal(3)[[1], [1, 1], [1, 2, 1]]
pascal(4)[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]
import mathhelp(math.comb)Help on built-in function comb in module math:
comb(n, k, /)
Number of ways to choose k items from n items without repetition and without order.
Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
to zero when k > n.
Also called the binomial coefficient because it is equivalent
to the coefficient of k-th term in polynomial expansion of the
expression (1 + x)**n.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
def pascal(base):
tr = [[1]]
for i in range(1, base):
previousline = tr[-1]
tr.append(nextline(previousline))
return trpascal(4)[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]
pascal(10)[[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]]
def formatline(line, maxsize):
return " ".join([str(item) for item in line]).center(maxsize)
def printtriangle(tr):
maxsize = len(tr[-1])
maxsize = maxsize + maxsize - 1
for line in tr:
print(formatline(line, maxsize))"text".rjust(10)' text'
"text".center(10)' text '
printtriangle(pascal(4)) 1
1 1
1 2 1
1 3 3 1
printtriangle(pascal(5)) 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
printtriangle(pascal(6)) 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Hints 1. use digit base formating that we used in printing squares/cubes 2. find out maximum number of digits in the biggest number in the triangle 3. maxsize used for centering will be recalculated? consider the size of last line in terms of chars and spaces!
other itearation patterns
words = "one two theree four five".split()for i in range(len(words)):
print(i, words[i])
0 one
1 two
2 theree
3 four
4 five
for i, w in enumerate(words):
print(i, w)0 one
1 two
2 theree
3 four
4 five
with open("poem.txt") as f:
for i, line in enumerate(f):
print(i, line, end="")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!
with open("poem.txt") as f:
for i, line in enumerate(f, start=1):
print(i, line, end="")1 The Zen of Python, by Tim Peters
2
3 Beautiful is better than ugly.
4 Explicit is better than implicit.
5 Simple is better than complex.
6 Complex is better than complicated.
7 Flat is better than nested.
8 Sparse is better than dense.
9 Readability counts.
10 Special cases aren't special enough to break the rules.
11 Although practicality beats purity.
12 Errors should never pass silently.
13 Unless explicitly silenced.
14 In the face of ambiguity, refuse the temptation to guess.
15 There should be one-- and preferably only one --obvious way to do it.
16 Although that way may not be obvious at first unless you're Dutch.
17 Now is better than never.
18 Although never is often better than *right* now.
19 If the implementation is hard to explain, it's a bad idea.
20 If the implementation is easy to explain, it may be a good idea.
21 Namespaces are one honking great idea -- let's do more of those!
for w in reversed(words):
print(w)five
four
theree
two
one
for w in words:
print(w)one
two
theree
four
five
with open("poem.txt") as f:
for line in reversed(f):
print(line, end="")--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[88], line 2 1 with open("poem.txt") as f: ----> 2 for line in reversed(f): 3 print(line, end="") TypeError: '_io.TextIOWrapper' object is not reversible