Skip to content

Commit 76c134f

Browse files
committed
Add some examples
- these may be helpful when explaining/understanding a concept.
1 parent 5d5e0d1 commit 76c134f

32 files changed

+460
-1
lines changed

examples

-1
This file was deleted.

examples/change_dirs.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import os
2+
3+
4+
current_working_dir = os.getcwd()
5+
6+
# change working directory
7+
# junk_dir = os.path.join(current_working_dir, 'junk')
8+
# os.chdir(junk_dir)
9+
# print(os.getcwd())
10+
11+
12+
# rename directories
13+
14+
# os.rename('my_dir', 'renamed_dir')
15+
16+
17+
# move directories with replace
18+
# os.replace('renamed_dir/junk', 'abcd')
19+
20+
21+
# remove, rmdir, rmdirs

examples/copy_file.py

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
with open('meme.jpg', 'rb') as original_file:
2+
with open('meme_copy.jpg', 'wb') as copy_file:
3+
for line in original_file:
4+
copy_file.write(line)

examples/data.txt

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Ada Lovelace: 834.345.1254 155-Street London, England
2+
Tessy Thomas: 892.345.3428 436-Street Alappuzha, Kerala
3+
Ritu Karidhal: 925.541.7625 662-Street Lucknow, Uttar Pradesh
4+
Muthayya Vanitha: 548-326-4584 919-Street Chennai, India

examples/dirs.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import os
2+
3+
print(__file__)
4+
5+
here_relative = os.path.relpath(__file__)
6+
here_real = os.path.realpath(__file__)
7+
8+
parent_dir = os.path.dirname(here_real)
9+
10+
text_file_loc = os.path.join(parent_dir, 'text.txt')
11+
12+
all_files = os.listdir(os.getcwd())

examples/emails/email.txt

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Just trying to test sending some text.
2+
3+
These contents were picked up from a file.
4+
5+
It seems learning python could be a lot more fun.

examples/emails/email_headers.txt

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
To: Bar <receiver@domain>
2+
From: Foo <sender@domain>
3+
Subject: Testing parsing headers from text template
4+
5+
Wow! This is exceptional
6+
7+
We can send emails by parsing text from a file.

examples/emails/parse_headers.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import smtplib
2+
import os
3+
from email.parser import BytesParser
4+
from email.policy import default
5+
6+
7+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
8+
HEADERS_PATH = os.path.join(BASE_DIR, 'email_headers.txt')
9+
10+
with open(HEADERS_PATH, 'rb') as fp:
11+
message = BytesParser(policy=default).parse(fp)
12+
13+
with smtplib.SMTP('localhost', 1025) as server:
14+
server.send_message(message)
+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import smtplib, ssl
2+
from email.message import EmailMessage
3+
import imghdr
4+
import os
5+
import mimetypes
6+
7+
8+
9+
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
10+
PATH = os.path.join(BASE_DIR, 'meme.jpg')
11+
12+
sender = os.getenv('EMAIL_SENDER')
13+
14+
msg = EmailMessage()
15+
msg['to'] = os.getenv('EMAIL_RECEIVER')
16+
msg['from'] = sender
17+
msg['subject'] = 'Test sending attachments through python'
18+
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
19+
msg.set_content('Please find the image attached below.')
20+
21+
22+
with open(PATH, 'rb') as fp:
23+
img_data = fp.read()
24+
25+
# Guess the content type based on the file's extension. Encoding
26+
# will be ignored, although we should check for simple things like
27+
# gzip'd or compressed files.
28+
ctype, encoding = mimetypes.guess_type(PATH)
29+
if ctype is None or encoding is not None:
30+
# No guess could be made, or the file is encoded (compressed), so
31+
# use a generic bag-of-bits type.
32+
ctype = 'application/octet-stream'
33+
maintype, subtype = ctype.split('/', 1)
34+
35+
msg.add_attachment(img_data, maintype=maintype, subtype=subtype)
36+
37+
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
38+
try:
39+
server.login(sender, os.getenv('EMAIL_PASS'))
40+
server.send_message(msg)
41+
42+
except smtplib.SMTPResponseException as exc:
43+
print('Exception occured during sending of email:', exc)

examples/emails/send_html.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import smtplib
2+
from email.message import EmailMessage
3+
import os
4+
5+
6+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
7+
HTML_PATH = os.path.join(BASE_DIR, 'email.html')
8+
9+
msg = EmailMessage()
10+
msg['To'] = 'receiver@domain'
11+
msg['From'] = 'sender@domain'
12+
msg['Subject'] = 'Testing large HTML email'
13+
msg.set_content('This is the text portion')
14+
15+
with open(HTML_PATH) as fp:
16+
msg.add_alternative(fp.read(), subtype='html')
17+
18+
19+
with smtplib.SMTP('localhost', 1025) as server:
20+
server.send_message(msg)

examples/emails/send_html_real.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import smtplib
2+
from email.message import EmailMessage
3+
import os
4+
5+
6+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
7+
HTML_PATH = os.path.join(BASE_DIR, 'email.html')
8+
9+
10+
msg = EmailMessage()
11+
msg['To'] = os.getenv('EMAIL_RECEIVER')
12+
msg['From'] = sender = os.getenv('EMAIL_SENDER')
13+
msg['Subject'] = 'Testing large HTML email'
14+
15+
with open(HTML_PATH) as fp:
16+
msg.add_alternative(fp.read(), subtype='html')
17+
18+
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
19+
server.login(sender, os.getenv('EMAIL_PASS'))
20+
server.send_message(msg)

examples/emails/send_image_real.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import smtplib, ssl
2+
from email.message import EmailMessage
3+
import imghdr
4+
import os
5+
6+
7+
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
8+
IMG_PATH = os.path.join(BASE_DIR, 'meme.jpg')
9+
10+
11+
msg = EmailMessage()
12+
msg['to'] = os.getenv('EMAIL_RECEIVER')
13+
msg['from'] = sender = os.getenv('EMAIL_SENDER')
14+
msg['subject'] = 'Test sending attachments through python'
15+
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
16+
msg.set_content('Please find the image attached below.')
17+
18+
with open(IMG_PATH, 'rb') as fp:
19+
img_data = fp.read()
20+
21+
msg.add_attachment(img_data, maintype='image', subtype=imghdr.what(None, img_data))
22+
23+
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
24+
try:
25+
server.login(sender, os.getenv('EMAIL_PASS'))
26+
server.send_message(msg)
27+
28+
except smtplib.SMTPResponseException as exc:
29+
print('Exception occured during sending of email:', exc)

examples/emails/send_text.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import smtplib
2+
from email.message import EmailMessage
3+
4+
5+
msg = EmailMessage()
6+
msg['to'] = 'receiver@domain'
7+
msg['from'] = 'sender@domain'
8+
msg['subject'] = 'Test sending text emails from python'
9+
msg.set_content('Hi! just checking to see if this works')
10+
11+
12+
with smtplib.SMTP('localhost', 1025) as server:
13+
server.send_message(msg)
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import smtplib
2+
from email.message import EmailMessage
3+
import os
4+
5+
6+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
7+
TEXT_PATH = os.path.join(BASE_DIR, 'email.txt')
8+
9+
msg = EmailMessage()
10+
msg['To'] = 'receiver@domain'
11+
msg['From'] = 'sender@domain'
12+
msg['Subject'] = 'Testing largetext from python'
13+
14+
with open(TEXT_PATH) as fp:
15+
msg.set_content(fp.read())
16+
17+
with smtplib.SMTP('localhost', 1025) as server:
18+
server.send_message(msg)

examples/emails/send_text_real.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import smtplib
2+
from email.message import EmailMessage
3+
import os
4+
5+
6+
msg = EmailMessage()
7+
msg['from'] = sender = os.getenv('EMAIL_SENDER')
8+
msg['to'] = os.getenv('EMAIL_RECEIVER')
9+
msg['subject'] = 'Testing text email through python'
10+
msg.set_content('Hi! let us hope this works.')
11+
12+
with smtplib.SMTP_SSL('smtp.gmail.com') as server:
13+
server.login(sender, os.getenv('EMAIL_PASS'))
14+
server.send_message(msg)

examples/files.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
with open('text.txt', 'r') as f:
2+
for num, line in enumerate(f):
3+
if line.find('text') > -1:
4+
print(f'The word text is present on the line {num + 1}')
5+
6+
7+
# print(content)

examples/meme.jpg

68.1 KB
Loading

examples/meme_copy.jpg

68.1 KB
Loading

examples/regular_expression.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import re
2+
3+
4+
text = '''
5+
this is a long string
6+
7+
a multi line string
8+
9+
46833
10+
11+
special characters that need to be escaped
12+
. * ^ + ? | [ ] { }
13+
14+
'''
15+
pattern = re.compile(r'\d{3}[\.-]\d{3}[\.-]\d{4}')
16+
17+
with open('data.txt') as f:
18+
for line in f:
19+
matches = pattern.finditer(line)
20+
for match in matches:
21+
print(match)
22+
# sentence = 'this is a SENTENCE 23'
23+
# sentence = 'aababcaabaaabc'
24+
# pattern = re.compile(r'a?')
25+
26+
# matches = pattern.finditer(sentence)
27+
# for match in matches:
28+
# print(match)

examples/rename.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import os
2+
3+
4+
cwd = os.chdir('/home/curious/Desktop/temp/module/junk')
5+
6+
7+
def create(prefix='file', extension='txt'):
8+
for num in range(1, 1001):
9+
filename = f'{prefix}_{num}.{extension}'
10+
with open(filename, 'x'):
11+
pass
12+
13+
14+
def rename():
15+
filenames = os.listdir(cwd)
16+
# 01_file.txt
17+
for filename in filenames:
18+
name, extension = filename.split('.')
19+
name, num = name.split('_')
20+
21+
num = num.zfill(2)
22+
os.rename(filename, f'{num}_{name}.{extension}')
23+
24+
25+
26+
def delete():
27+
filenames = os.listdir(cwd)
28+
for filename in filenames:
29+
os.remove(filename)

examples/sockets/client.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import socket
2+
3+
4+
HOST = socket.gethostbyname(socket.gethostname())
5+
PORT = 9999
6+
7+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
8+
client.connect((HOST, PORT))
9+
10+
client.sendall('Hi'.encode())
11+
data = client.recv(1024)
12+
print(f'Received from the server: {data.decode()}')

examples/sockets/server.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import socket
2+
import concurrent.futures
3+
4+
5+
HOST = socket.gethostbyname(socket.gethostname())
6+
PORT = 9999
7+
8+
9+
def handle_client(conn, addr):
10+
with conn:
11+
print(f'Connected from client:{addr}')
12+
while True:
13+
msg = conn.recv(1024)
14+
if not msg:
15+
print(f'Connection closed from {addr}')
16+
break
17+
print(f'Received: {msg.decode()}')
18+
conn.sendall('Hi from server'.encode())
19+
20+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
21+
server.bind((HOST, PORT))
22+
server.listen()
23+
print(f'Server is listening at {HOST}:{PORT}')
24+
while True:
25+
conn, addr = server.accept()
26+
with concurrent.futures.ThreadPoolExecutor() as executor:
27+
executor.submit(handle_client, conn, addr)

examples/special_characters.txt

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
Special characters in default mode.
2+
3+
4+
. - matches every character except newline
5+
\w - every character(a-z, A-Z, 0-9,_)
6+
\W - not a character
7+
\d - digit
8+
\D - not a digit
9+
\s - space character(including tabs and newlines)
10+
\S - not a space character
11+
12+
13+
\b - boundary of a word
14+
\B - not a boundary
15+
^ - starting of the string
16+
$ - ending of the string
17+
18+
[] - Matches Characters in brackets
19+
[^ ] - Matches Characters NOT in brackets
20+
| - Either Or
21+
( ) - Group
22+
23+
Quantifiers
24+
-----------
25+
26+
* - causes the preceding RE to match 0 or more times.
27+
+ - preceding RE matches atleast 1 time.
28+
? - preceding RE matches 0 or 1 time.
29+
{m} - preceding RE matches exactly m times.
30+
{m, n} - preceding RE matches atleast m times and atmost n times.

0 commit comments

Comments
 (0)