Skip to content

Commit 579d99a

Browse files
committed
adding lecture 3
1 parent 7e2e5ee commit 579d99a

File tree

10 files changed

+332
-0
lines changed

10 files changed

+332
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
## General explanation
2+
# https://docs.python.org/3/library/exceptions.html
3+
# log module short explanation and example (import logging)
4+
# https://docs.python.org/3/library/logging.html#logging.Logger.error
5+
6+
# try:
7+
# pass
8+
# except Exception:
9+
# pass
10+
# else:
11+
# pass
12+
# finally:
13+
# pass
14+
15+
## Let's try to open file
16+
17+
# f = open('test.txt ','r')
18+
19+
## Let's handle this with general exception
20+
# try:
21+
# f = open('test.txt','r')
22+
# except Exception:
23+
# print("Sorry this file isn't exist!")
24+
25+
## Let's handle it with specific exeption
26+
# try:
27+
# f = open('test.txt ','r')
28+
# except FileNotFoundError:
29+
# print("Sorry this file isn't exist!")
30+
31+
## Let's add more code , with differnt broken line
32+
# try:
33+
# f = open('test.txt','r') # file open fixed
34+
# var = bad_var # bad varibale
35+
# except FileNotFoundError as e: # add and show as e, print(e)
36+
# print("Sorry this file isn't exist!")
37+
# print(e)
38+
# except Exception as e: # add and show as e, print(e)
39+
# print("Something went wrong!")
40+
# print(e)
41+
42+
## Else block
43+
# try:
44+
# f = open('test.txt','r')
45+
# except Exception as e:
46+
# print(e)
47+
# else:
48+
# print(f.read())
49+
# f.close()
50+
51+
## Finally block
52+
# try:
53+
# f = open('test.txt','r')
54+
# except Exception as e:
55+
# print(e)
56+
# else:
57+
# print(f.read())
58+
# f.close()
59+
# finally:
60+
# print("Executing Finally...!")
61+
62+
## Log module
63+
64+
# import logging
65+
66+
# logging.basicConfig(filename='example.log',level=logging.DEBUG)
67+
68+
# try:
69+
# f = open('test.txt','r')
70+
# except Exception as e:
71+
# logging.error(e)
72+
# else:
73+
# print(f.read())
74+
# logging.info("end file {} manipulation".format(f.name))
75+
# f.close()
76+
# finally:
77+
# logging.info("from finally block of exception")

exeption_logging/test_.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Just test file ! for exception explanation !

files_os_module/test.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
1) This is a test file
2+
2) This is a second line
3+
3) This is a third line
4+
4) This is a fourth line
5+
4) This is a five line
6+
6) This is a six line
7+
7) This is a seven line
8+
8) This is a eight line
9+
9) This is a nine line
10+
10) This is a ten line
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
## First option to work with file,
2+
# open file r - read, a - append, w - write to file , r+ - both read/write
3+
# need close() expression, files descriptor etc.
4+
# f = open('test.txt','r')
5+
# print(f.name)
6+
# print(f.mode)
7+
# f.close() # possible leak for max file descriptors in system, Don't Leak file discriptor
8+
9+
10+
## Context manager explanation auto close ---> Good Practice!!!
11+
# with open('test.txt','r') as f:
12+
# pass
13+
# print(f.closed)
14+
# print(f.read())
15+
16+
## read and print whole file :
17+
# with open('test.txt','r') as f:
18+
# f_contents = f.read()
19+
# print(f_contents)
20+
21+
## read and print line by line file:
22+
# with open('test.txt','r') as f:
23+
# with open('test.txt','r') as f:
24+
# # f_contents = f.readlines()
25+
# f_contents = f.readlines()
26+
# print(f_contents)
27+
28+
## read and print single line, first one every time we call function readline will read next line (copy and show)
29+
# with open('test.txt','r') as f:
30+
# f_contents = f.readline()
31+
# print(f_contents) # add end=''
32+
# f_contents = f.readline()
33+
# print(f_contents)
34+
35+
## Read extreamly long file: if we read at once, we can run out of memory
36+
# with open('test.txt','r') as f:
37+
# for line in f:
38+
# print(line, end='')
39+
40+
## More control for reading , explanation of read buffer
41+
# with open('test.txt','r') as f:
42+
# f_contents = f.read()
43+
# f_contents = f.read(100) # copy and explain
44+
# print(f_contents, end='')
45+
46+
## More contr eol for big files with while and EOF condition in while loop, also f.tell() and f.seek()
47+
# with open('test.txt','r') as f:
48+
# size_to_read = 10
49+
# f_contents = f.read(size_to_read)
50+
51+
# print(f_contents)
52+
# print(f.tell()) # tell curent position in the file ,show f.seek(0)
53+
# f_contents = f.read(size_to_read)
54+
# print(f_contents)
55+
56+
# while len(f_contents) > 0:
57+
# print(f_contents, end='*')
58+
# f_contents = f.read(size_to_read) # without it infinite loop, by the end of the file it will return epmty string
59+
# and hit our while conditional
60+
61+
## Write to file, w flag.. let's create new file (use a flag to append)
62+
# with open('test2.txt', 'w') as f:
63+
# f.write('Test') # double it and show f.seek() not common usefull in write mode (show with one letter R)
64+
65+
## Copy file or work with both read/write
66+
# with open('test.txt', 'r') as rf, open('text_copy.txt', 'w') as wf: # in one line
67+
68+
# with open('test.txt', 'r') as rf:
69+
# with open('text_copy.txt', 'w') as wf:
70+
# for line in rf:
71+
# wf.write(line)
72+
#####
73+
###
74+
## module os introduction
75+
# import os
76+
77+
# print(os.getcwd())
78+
79+
# os.system('dir') # Execute shell command
80+
81+
## Make folder
82+
# os.makedirs('my_dir')
83+
84+
## Print environment variable
85+
# print(os.environ)
86+
87+
## Make intermediate folders:
88+
# suppose you want to make a subfolder under your home folder: $HOMEPATH/python-project/project1/temp
89+
# folder_name = os.path.join(os.environ['HOMEPATH'],'python-project','project1','temp')
90+
# os.makedirs(folder_name)
91+
92+
## Walking throught directories and files :
93+
# for dirpath, dirname, filename in os.walk(os.environ['HOMEPATH']):
94+
# print('Current path',dirpath)
95+
# print('Directories:', dirname)
96+
# print('Files:', filename)
97+
# print()
98+
99+
## files stats
100+
# print(os.stat('test.txt'))
101+
# print(os.stat('test.txt').st_size)
102+
# print(os.stat('test.txt').st_mtime)
103+
104+
# from datetime import datetime
105+
# mod_time = os.stat('test.txt').st_mtime
106+
# print(datetime.fromtimestamp(mod_time))
107+
# mod_time = os.stat('test.txt').st_mtime
108+
# print(datetime.fromtimestamp(mod_time))
109+
110+
## some usefull os.path :
111+
# print(os.path.basename(os.getcwd()))
112+
# print(os.path.dirname(os.getcwd())) # only dir name
113+
# print(os.path.split(os.getcwd()))
114+
# print(os.path.exists(os.getcwd()))
115+
# print(os.path.isdir('/Users'))

requests/dog.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import requests
2+
3+
api_url = "http://shibe.online/api/shibes?count=1"
4+
5+
params = {"count": 10}
6+
response = requests.get(api_url, params=params)
7+
8+
status_code = response.status_code
9+
print("status code: ", status_code)
10+
11+
response_json = response.json()
12+
print(response_json)
13+
print(response.url)

requests/git_api_exampe.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
"""
2+
TIP: Don't forget to run: pip install requests!
3+
4+
A small Python program that uses the GitHub search API to list
5+
the top projects by language, based on stars.
6+
7+
GitHub Search API documentation: https://developer.github.com/v3/search/
8+
9+
Additional parameters for searching repos can be found here:
10+
https://help.github.com/en/articles/searching-for-repositories#search-by-number-of-stars
11+
12+
Note: The API will return results found before a timeout occurs,
13+
so results may not be the same across requests, even with the same query.
14+
15+
Requests to this endpoint are rate limited to 10 requests per
16+
minute per IP address.
17+
"""
18+
19+
import requests
20+
21+
GITHUB_API_URL = "https://api.github.com/search/repositories"
22+
23+
24+
def create_query(languages, min_stars=50000):
25+
"""
26+
Create the query string for the GitHub search API,
27+
based on the minimum amount of stars for a project, and
28+
the provided programming languages.
29+
30+
An example search query looks like:
31+
stars:>50000 language:python language:javascript
32+
"""
33+
query = f"stars:>{min_stars} "
34+
35+
for language in languages:
36+
query += f"language:{language} "
37+
38+
return query
39+
40+
41+
def repos_with_most_stars(languages, sort="stars", order="desc"):
42+
query = create_query(languages)
43+
44+
# Define the parameters we want to be part of our URL
45+
parameters = {"q": query, "sort": sort, "order": order}
46+
47+
# Pass in the query and the parameters as part of the request.
48+
response = requests.get(GITHUB_API_URL, params=parameters)
49+
status_code = response.status_code
50+
51+
# Check if the rate limit was hit. Applies only for students running this code
52+
# in the in-person course.
53+
if status_code == 403:
54+
raise RuntimeError("Rate limit reached. Please wait a minute and try again.")
55+
if status_code != 200:
56+
raise RuntimeError(f"An error occurred. HTTP Status Code was: {status_code}.")
57+
else:
58+
response_json = response.json()
59+
records = response_json["items"]
60+
return records
61+
62+
63+
if __name__ == "__main__":
64+
languages = ["python", "javascript", "ruby", "go"]
65+
results = repos_with_most_stars(languages)
66+
67+
for result in results:
68+
language = result["language"]
69+
stars = result["stargazers_count"]
70+
name = result["name"]
71+
72+
print(f"-> {name} is a {language} repo with {stars} stars.")

requests/simple_example.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import json
2+
import requests
3+
4+
response = requests.get("https://jsonplaceholder.typicode.com/todos")
5+
todos = json.loads(response.text)
6+
print(todos)

scripts/words_count.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ def main():
2020
lines = f.readlines()
2121
for line in lines:
2222
for word in line.split():
23+
word = word.replace(".","")
2324
if word.rstrip() in alpha_statistic.keys():
2425
alpha_statistic[word]+=1
2526
else:

working_with_json/demo.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"firstName": "Jane",
3+
"lastName": "Doe",
4+
"hobbies": ["running", "sky diving", "singing"],
5+
"age": 35,
6+
"children": [
7+
{
8+
"firstName": "Alice",
9+
"age": 6
10+
},
11+
{
12+
"firstName": "Bob",
13+
"age": 8
14+
}
15+
]
16+
}

working_with_json/json_demo.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import json
2+
3+
## Simple serialization
4+
# data = {
5+
# "president": {
6+
# "name": "Zaphod Beeblebrox",
7+
# "species": "Betelgeusian"
8+
# }
9+
# }
10+
11+
# with open("data_file.json", "w") as write_file:
12+
# json.dump(data, write_file)
13+
# # continue using this serialized JSON data in your program,
14+
# # you could write it to a native Python str object.
15+
# json_string = json.dumps(data)
16+
# print(json_string)
17+
18+
## Simple deserialization example
19+
with open("demo.json","r") as read_file:
20+
data = json.load(read_file)
21+
print(data)

0 commit comments

Comments
 (0)