Sep 18-20 2017 Vikrant Patil
These notes are available online at http://notes.pipal.in/2017/vmware-python
© Pipal Academy LLP
%%file three.txt
one
two
three
fhandle = open("three.txt")
fhandle.read() # will read complete contents of file in single statement
fhandle.read()
fhandle.close()
!python -c "import this" > data.txt
filehandle = open("data.txt")
filehandle.readline()
lines = filehandle.readlines()
print(lines)
lines
filehandle = open("data.txt")
for line in filehandle.readlines():
words = line.strip().split()
print(len(words))
python cat.py three.txt
one
two
three
python head.py 5 data.txt
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
%%file cat.py
import sys
def print_file(filename):
f = open(filename)
for line in f.readlines():
print(line.strip())
if __name__ == "__main__":
print_file(sys.argv[1])
!python cat.py three.txt
%%file head.py
import sys
def head(filename, n):
f = open(filename)
for line in f.readlines()[:n]:
print(line.strip())
if __name__ == "__main__":
head(sys.argv[1], int(sys.argv[2]))
!python head.py data.txt 5
%%file wc.py
"""
module wc implements unix equivalnet of wc cammand
"""
import sys
def line_count(f):
lines = open(f).readlines()
return len(lines)
def word_count(f):
words = open(f).read().split()
return len(words)
def char_count(f):
return len(open(f).read())
if __name__ == "__main__":
f = sys.argv[1]
print(line_count(f), word_count(f), char_count(f))
!python wc.py data.txt
import os
files = [f for f in os.listdir(".") if f.endswith(".txt")]
files
import wc
max(files, key=wc.line_count)
max(files, key=wc.word_count)
max(files, key=wc.char_count)
f = open("primes.txt", "w")
f.write("two\n")
f.write("five\n")
f.write("three\n")
f.close()
!python cat.py primes.txt
f = open("primes.txt", "a")
f.write("seven\n")
f.write("eleven\n")
f.close()
!python cat.py primes.txt
Similarly we can read and write binary files with following mode
rb => read in binary modewb => write in binary modeab => append in binary modeopen("primes.txt", "r").read() # read in text mode
open("primes.txt", "rb").read()
f = open("binarydata.bin", "wb")
f.write(b'x025x082')
f.close()
open("binarydata.bin", "rb").read()
f = open("binarydata.bin", "ab")
f.write(b'hello')
f.close()
open("binarydata.bin", "rb").read()
with open("primes.txt", "a") as f:
f.write("thirteen")
!python cat.py primes.txt
with open("regional.txt", "w", encoding='utf-8') as regional:
regional.write("\u0c05\u0c06")
!python cat.py regional.txt
open("regional.txt", encoding='utf-8').read()
open("regional.txt", 'rb').read()
author = {'name':"lewis carrol",
"books": ["alice in wonderland", "looking through the glass"],
"language" : "English"}
author['name'] = "lewis"
author
del author['language']
author
'name' in author
author['name']
author.get('name')
author['language']
author.get("language", "English")
author
author.get("language")
author.get("language") == None
author.get("books")
del author['books']
author
author.get("books", [])
d = {"one":1, "two":2, "three":3}
for key in d.keys():
print(key, d[key])
for values in d.values():
print(values)
for key, value in d.items():
print(key, value)
What if we iterate over dictionary directly?
for item in d:
print(item)
numbers = [("one", 1), ("two", 2), ("three", 3)]
dict(numbers)
items = ("pen", "pencil", "colorbox")
prices = (25, 10, 50)
cart = dict(zip(items, prices))
cart
for item, price in cart.items():
print(item.rjust(8), price)
print("-"*12)
print("Total".rjust(8), sum(cart.values()))
can you write a function unzip which retuns two separate lists of keys and values
def unzip(d):
return list(d.keys()), list(d.values())
unzip(cart)
%%file words.txt
five
five four
five four three
five four three two
five four three two one
six seven eight nine
six seven eight
six seven
six
%%file wordfreq.py
import sys
def read_words(file):
return open(file).read().split()
def wordfreq(words):
freq = {}
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
return freq
if __name__ == "__main__":
words = read_words(sys.argv[1])
freq = wordfreq(words)
print(freq)
!python wordfreq.py words.txt
%%file wordfreq.py
import sys
def read_words(file):
return open(file).read().split()
def wordfreq(words):
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq
if __name__ == "__main__":
words = read_words(sys.argv[1])
freq = wordfreq(words)
print(freq)
!python wordfreq.py words.txt
import wordfreq
words = wordfreq.read_words("words.txt")
freq = wordfreq.wordfreq(words)
for w, f in freq.items():
print(w, f)
for k,v in sorted(freq.items()):
print(k.rjust(5), v)
for k, v in sorted(freq.items(), key = lambda x:x[1]):
print (k.rjust(5), v)
for k, v in sorted(freq.items(), key = lambda x:x[1], reverse=True):
print (k.rjust(5), v)
for k, v in sorted(freq.items(), key = lambda x:x[1], reverse=True):
print (k.rjust(5), v, "*"*v)
Grouping all keys based on values
team = {"david":"USA", "anand":"India","linus":"USA","nouful":"India","alice":"UK"}
[name for name in team.keys() if team[name]=="India"]
[name for name in team.keys() if team[name]=="USA"]
x = [1,2,3]
y = x
y.append(4)
print(x)
x = [1, 2, 3, 4]
y = x
y = [1, 2, 3]
print(x)
x = 1
y = x
y = 2
print(x)
class Complex:
def __init__(self, r, i):
self.real = r
self.imaginary = i
def get_real(self):
return self.real
def get_imaginary(self):
return self.imaginary
p = Complex(10, 5)
class Dummy:
pass
d = Dummy()
print(d)
class Dummy:
def __init__(self):
pass
d = Dummy()
print(d)
p = Complex(10, 5)
type(p)
isinstance(p, Complex)
isinstance(p, Dummy)
class Complex:
def __init__(self, r, i):
self.real = r
self.imaginary = i
def get_real(self):
return self.real
def get_imaginary(self):
return self.imaginary
def display(self):
print(self.real, "+", str(self.imaginary) + "j")
def add(self, c):
r = self.real + c.get_real()
i = self.imaginary + c.get_imaginary()
return Complex(r, i)
p = Complex(10, 5)
p1 = Complex(3, 4)
p2 = p.add(p1)
p1.display()
p2.display()
p.display()
%%file bank0.py
balance = 0
def deposit(amount):
global balance
balance = balance + amount
def withdraw(amount):
global balance
balance = balance - amount
def get_balance():
global balance
return balance
def main():
deposit(100)
withdraw(40)
print(get_balance())
deposit(20)
print(get_balance())
if __name__ =="__main__":
main()
!python bank0.py
%%file bank1.py
def make_account():
return {"balance":0}
def deposit(account , amount):
account['balance'] = account['balance'] + amount
def withdraw(account, amount):
account['balance'] -= amount
def get_balance(account):
return account['balance']
def main():
a1 = make_account()
deposit(a1, 100)
withdraw(a1, 40)
print(get_balance(a1))
deposit(a1, 20)
print(get_balance(a1))
a2 = make_account()
deposit(a2, 1000)
withdraw(a2, 200)
print(get_balance(a2))
if __name__ =="__main__":
main()
!python bank1.py
import time
time.time()
t = Timer()
t.start()
do_some_stuff()
t.stop()
print("Time taken: ", t.get_time_taken())
import time
class Timer:
def start(self):
self.starttime = time.time()
def stop(self):
self.endtime = time.time()
def get_time_taken(self):
return self.endtime - self.starttime
t = Timer()
t.start()
s = 0
for i in range(1000):
for j in range(10000):
s += i*j
t.stop()
print("Time taken:", t.get_time_taken())
z
int("Hello")
"2" * "3"
b = "2"
c = "3"
try:
a = b*c
except TypeError as e:
a = 1
print("Handled TypeError", e)
except ValueError as e:
b = 0
print("Handled ValueError", e)
print(a)
def parseinteger(strnum):
try:
return int(strnum)
except ValueError as e:
return 0
def read_with_missing(filename):
with open(filename) as file:
return [parseinteger(line.strip()) for line in file.readlines()]
%%file missing.txt
1
2
3
4
5
N/A
6
6
7
Nan
8
9
read_with_missing("missing.txt")
%%file command.py
import argparse
def parse_args():
p = argparse.ArgumentParser()
p.add_argument("word", help="word which command.py will print to screen",
type=str)
return p.parse_args()
def print_word(word):
print(word)
def main():
args = parse_args()
print(args)
print_word(args.word)
if __name__ == "__main__":
main()
!python command.py hello
!python command.py
!python command.py -h
%%file command.py
import argparse
def parse_args():
p = argparse.ArgumentParser()
p.add_argument("word", help="word which command.py will print to screen",
type=str)
p.add_argument("-u", "--username",
help = "User name for executing this command")
p.add_argument("--debug",
help="Debug mode",
action="store_true")
return p.parse_args()
def print_word(word):
print("From default :", word)
def print_user(user):
print("From -u :", user)
def print_debug(debug):
if debug:
print("From debug")
def main():
args = parse_args()
print(args)
print_word(args.word)
print_user(args.username)
print_debug(args.debug)
if __name__ == "__main__":
main()
!python command.py -h
!python command.py -u vikrant --debug hello
!python command.py hello
from urllib.request import urlopen
response = urlopen("http://httpbin.org/html")
response
contents = response.read()
contents[:100]
html = contents.decode("utf-8")
print(html[:400])
response.status
There is third party library requests
pip3 install requests
import requests
response = requests.get("http://httpbin.org/html")
print(response.text[:400])
response.headers
response.status_code
response = requests.get("http://httpbin.org/get", params={"param1":"hello", "param2":"hello2"})
print(response.text)
response = requests.post("http://httpbin.org/post", data="some string")
print(response.text)
url = "https://api.github.com/orgs/vmware/repos"
repos = requests.get(url).json()
type(repos)
for repo in repos:
print(repo['full_name'], repo['forks'])
reps = sorted(repos, key=lambda r:r['forks'], reverse=True)[:5]
for r in reps:
print(r['full_name'], r['forks'])