Solutions for os, subprocess, requests exercises

Ex 1: Alphabet List Comprehensions

 1# 1. Create a list of capital letters in the english alphabet
 2
 3[chr(i) for i in range(65,91)]
 4
 5# 2. Create a list of capital letter from the english aplhabet, but exclude 4 with the Unicode code point of either 70, 75, 80, 85.
 6
 7[chr(i) for i in range(65,91) if i not in [70,75,80,85]]
 8
 9# 3. Create a list of capital letter from from the english aplhabet, but exclude every second between F & O
10
11[chr(i) for i in range(65,91) if i not in range(70,80,2)]

Ex 2: Clothes List Comprehension

1colors = ['Black', 'White']
2sizes = ['s', 'm', 'l', 'xl']
3
4# 1
5[(c,s) for c in colors for s in sizes]
6
7# 2
8soled_out = [('Black', 'm'), ('White', 's')]
9[c,s) for c in colors for s in sizes if (c,s) not in soled_out]

Ex 5: OS Module exercise

 1import os
 2
 3#1
 4os.mkdir('os_exercises.')
 5#2
 6os.chdir('os_exercises')
 7open('exercise.py', 'w')
 8#3
 9x = input('Please write something to the file: ')
10with open('exercise.py', 'w') as f:
11    f.write(x)
12
13#4 
14x = input('Please write something More to anoter file: ') 
15with open('exercise2.py', 'w') as f:
16    f.write(x)
17
18#5
19with open('exercise.py', 'r') as f1:
20    with open('exercise2.py', 'r' ) as f2:
21        print(f1.read() + f2.read())
22

Ex 7: Simple scraber with requests

 1
 2import requests
 3import os
 4
 5# fetch the html from a url
 6req = requests.get('https://clbokea.github.io/exam/assignment_2.html')
 7text = req.text
 8
 9img_url_list = [] 
10
11text_list = text.split('img')
12
13def locate_image(e):
14    i = e.find('"')
15
16    # cut after  'src="' to end of the img_url  
17    img_url = e.split('"')
18    img_url = img_url[1]
19    img_url_list.append(img_url)
20
21
22for e in text_list:
23    if 'src' in e:
24        locate_image(e)
25
26# print(img_url_list)
27
28# Create a src directory for the images
29os.mkdir('src')
30os.chdir('src')
31
32for i in img_url_list:
33    # get the image
34    req = requests.get(f'https://clbokea.github.io/exam/{i}', stream=True)
35
36    # write image to file
37    with open(i[4:], 'wb') as f:
38        for chunk in req:
39            f.write(chunk)
40
41os.chdir('..')
42
43with open('index.html', 'w') as f:
44    f.write(text)
45
46
47
48
49