<repo_name>DanielJWagener/automate-the-boring-stuff-with-python<file_sep>/email/smtpExample.py
import smtplib

conn = smtplib.SMTP('smtp.gmail.com', 587)

conn.ehlo()

conn.starttls()

print(conn.login('<EMAIL>', '<password>'))

conn.sendmail('<EMAIL>', '<EMAIL>',
              'Subject: Hi me\n\nDear Daniel, \nWell, here ya go')

conn.quit()
<file_sep>/files/walking.py
import os

os.chdir('/home/daniel/Coding/automate-the-boring-stuff/files')

for folderName, subfolders, filenames in os.walk('./walkMe'):
    print('The folder is ' + folderName)
    print('The subfolders in ' + folderName + ' are: ' + str(subfolders))
    print('The filenames in %s are: %s' % (folderName, str(filenames)))
    print()
<file_sep>/README.md
# Automate the Boring Stuff with Python.

This is simply a repository of a code I write while going through Al Sweigart's Udemy course.
<file_sep>/excel-word-pdf/readPDF.py
import PyPDF2
import os

os.chdir('/home/daniel/Downloads')

pdfFile = open('meetingminutes1.pdf', 'rb')

reader = PyPDF2.PdfFileReader(pdfFile)

print(reader.numPages)

page = reader.getPage(0)
print(page.extractText())


# Print entire PDF
for pageNum in range(reader.numPages):
    print(reader.getPage(pageNum).extractText())

pdfFile.close()
<file_sep>/email/checkInbox.py
import imapclient
import pyzmail

conn = imapclient.IMAPClient('imap.gmail.com', ssl=True)
conn.login('<EMAIL>', '<<PASSWORD>>')
print(conn.select_folder('INBOX', readonly=True))

UIDs = conn.search(['SINCE', '10-Mar-2020'])

rawMessage = conn.fetch([38642], ['BODY[]', 'FLAGS'])

message = pyzmail.PyzMessage.factory(rawMessage[38642][b'BODY[]'])

print(message.get_subject())

print(message.text_part.get_payload().decode('UTF-8'))
<file_sep>/files/deleting.py
import os
import shutil
import send2trash


os.chdir('/home/daniel/Coding/automate-the-boring-stuff/files')

# os.rmdir('./asdf')

# shutil.rmtree('./asdf')

send2trash.send2trash('./trashMe.txt')
<file_sep>/web-scraping/downloadingWithRequests.py
import requests
import os

os.chdir('/home/daniel/Coding/automate-the-boring-stuff/web-scraping')

res = requests.get('http://automatetheboringstuff.com/files/rj.txt')
# print(res.status_code)

res.raise_for_status()

outputFile = open('RomeoAndJuliet.txt', 'wb')

for chunk in res.iter_content(10000):
    outputFile.write(chunk)

outputFile.close()
<file_sep>/regex/groups.py
import re

message = "Call me 123-123-1234 because that's totes a real phone number."

phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')

mo = phoneNumRegex.search(message)

# Not zero indexed wtf
print("The area code is %s and the rest of the phone number is %s" %
      (mo.group(1), mo.group(2)))

# Escaping parentheses
message2 = "Call me (123) 123-1234 because that's totes a real phone number."

parenthesesPhoneNumRegex = re.compile(r'\(\d\d\d\) \d\d\d-\d\d\d\d')
mo2 = parenthesesPhoneNumRegex.search(message2)

print('Look ma, escaped parentheses: %s' % (mo2.group()))

# Pipe Character
batRegex = re.compile(r'Bat(mobile|copter|man|bat)')
mo3 = batRegex.search(r"Let's get in the Batmobile")

print("Today's bat-word is: %s" % (mo3.group()))
<file_sep>/excel-word-pdf/editExcel.py
import openpyxl
import os

os.chdir('/home/daniel/Coding/automate-the-boring-stuff/excel-word-pdf')

# Create new workbook
wb = openpyxl.Workbook()


sheet = wb.get_sheet_by_name('Sheet')
sheet['A1'] = 42
sheet['A2'] = 'Hello'


sheet2 = wb.create_sheet()
sheet2.title = "New Sheet"

wb.save('example3.xlsx')
<file_sep>/gui-automation/keyboard.py
import pyautogui

pyautogui.click(200, 200)
pyautogui.typewrite('Hello, world!', interval=0.05)

pyautogui.hotkey('ctrl', 'n')
<file_sep>/files/shelfFiles.py
import os
import shelve

os.chdir('/home/daniel/Coding/automate-the-boring-stuff/files')

shelfFile = shelve.open('catdata')
# shelfFile['cats'] = ['Emma', 'Byron']
print(shelfFile['cats'])
shelfFile.close()
<file_sep>/regex/classes.py
import re

lyrics = """On the 12th day of Christmas my true love sent to me
12 Lords a leaping, 11 ladies dancing, 10 pipers piping
9 drummers drumming, 8 maids a milking
7 swans a swimming, 6 geese a laying
And 5 gold rings, 4 calling birds, 3 French hens, 2 turtle doves
And a partridge in a pear tree"""

xmasRegex = re.compile(r'\d+\s\w+')

print(xmasRegex.findall(lyrics))


# Make your own character class:
vowelRegex = re.compile(r'[aeiouAEIOU]')
print(vowelRegex.findall(lyrics))

doubleVowelREgex = re.compile(r'[aeiouAEIOU]{2}')
print(doubleVowelREgex.findall(lyrics))

notVowelRegex = re.compile(r'[^aeiouAEIOU]')
print(notVowelRegex.findall(lyrics))
<file_sep>/web-scraping/amazonPriceScraper.py
import bs4
import requests


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
}

res = requests.get(
    'https://www.amazon.com/Automate-Boring-Stuff-Python-2nd-ebook/dp/B07VSXS4NK', headers=headers)

res.raise_for_status()

soup = bs4.BeautifulSoup(res.text, 'html.parser')
soup2 = bs4.BeautifulSoup(soup.prettify(), "html.parser")

elems = soup.select(
    '#mediaNoAccordion > div.a-row > div.a-column.a-span4.a-text-right.a-span-last > span.a-size-medium.a-color-price.header-price')


print(elems)
print(elems[0].text.strip())
<file_sep>/gui-automation/mouse.py
import pyautogui

width, height = pyautogui.size()

# Move mouse to position
# pyautogui.moveTo(400, 500, duration=5)

# Move mouse up 100px
# pyautogui.moveRel(0, -100)

# Get mouse position
print(pyautogui.position())

pyautogui.click(584, 99)
<file_sep>/dictionaries/characterCounter.py
from pprint import pprint

message = "The quick brown fox jumped over the lazy dog"

count = {}

for character in message.upper():
    count.setdefault(character, 0)
    count[character] = count[character] + 1

pprint(count)
<file_sep>/files/os.py
import os

lolFile = open('/home/daniel/lol.txt')

content = lolFile.read()
print(content)

lolFile.close()

# Write mode
# lolFile = open('/home/daniel/lol.txt', 'w')

# Appened mode
# lolFile = open('/home/daniel/lol.txt', 'a')

lmaoFile = open('/home/daniel/lmao.txt', 'w')
# lmaoFile.write('Ayyyyyyy lmao')
lmaoFile.close

print(os.getcwd())
os.chdir('/home/daniel/Coding/automate-the-boring-stuff/files')

roflFile = open('deadhead.txt', 'a')
roflFile.write("Hooray for you\n")
roflFile.close()
<file_sep>/regex/repetition.py
import re

# ? (match preceding group zero or one times)
batRegex = re.compile(r'Bat(wo)?man')
mo = batRegex.search('The Adventures of Batwoman')
print('Find Batman or Batwoman:', mo.group())


phoneNumRegexOptionalAreaCode = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d')
mo2 = phoneNumRegexOptionalAreaCode.search(
    "This phone number, 456-1234, has no area code.")
print("But that's fine, we can do without.", mo2.group())


# * (match zero or more)
rockyHorrorRegex = re.compile(r'antici(.)*( )*pation')
mo3 = rockyHorrorRegex.search("antici....... pation")
print("I see you shiver with", mo3.group())
mo4 = rockyHorrorRegex.search("Whatever, anticipation")
print("No shivers here:", mo4.group())

# + (match one or more)
hamburgersRegex = re.compile(r'(\d)+ hamburgers')
mo5 = hamburgersRegex.search('Gimme 100 hamburgers')
print('Order up:', mo5.group())

# {x} (match specific number of times)
ellipsesRegex = re.compile(r'(\.){3}')
print(ellipsesRegex.search("Idk man...").group())

# {x, y} (match a range of times)
longEllipsesRegex = re.compile(r'(\.){3,}')
print(longEllipsesRegex.search("Idk bro........").group())

# Greedy and non-greedy matches
greedyMoo = re.compile(r'M(o){2,10}')
nongreedyMoo = re.compile(r'M(o){2,10}?')
moo = "Mooooooo"
print("Greedy match:", greedyMoo.search(moo).group())
print("Non-greedy match:", nongreedyMoo.search(moo).group())
<file_sep>/excel-word-pdf/readExcel.py
import openpyxl
import os

os.chdir('/home/daniel/Coding/automate-the-boring-stuff/excel-word-pdf')

workbook = openpyxl.load_workbook('example.xlsx')
sheet = workbook.get_sheet_by_name('Sheet1')

for i in range(1, 8):
    print(i, sheet.cell(row=i, column=2).value)
<file_sep>/excel-word-pdf/readWord.py
import docx
import os

os.chdir('/home/daniel/Downloads')

d = docx.Document('demo.docx')

print(d.paragraphs[0].text)

p = d.paragraphs[1]

# A run is a segment of styled text (e.g. bold, italic)
print(p.runs[1].text)  # bold

# We can change styles and text:
p.runs[3].underline = True
p.runs[3].text = 'italic and underline'

d.save('demo2.docx')
<file_sep>/files/copyMove.py
import shutil
import os

os.chdir('/home/daniel/Coding/automate-the-boring-stuff/files')
# os.makedirs(os.getcwd() + '/dest')

# shutil.copy('deadhead.txt', './dest')

# shutil.copytree("./dest", "./dest-backup")

# Rename a file by "moving" it to the folder it's already in and giving it a new name
shutil.move('./dest-backup/deadhead.txt', './dest-backup/deadhead-backup.txt')
<file_sep>/regex/dotStar.py
import re


# ^ (beginning pattern)
beginsWithHelloRegex = re.compile(r'^Hello')
print(beginsWithHelloRegex.search("Hello there!"))


# $ (ending pattern)
endsWithWorldRegex = re.compile(r'world$')
print(endsWithWorldRegex.search('Hello, world'))


# Combine to match an entire string
allDigitsRegex = re.compile(r'^\d+$')
print(allDigitsRegex.search('234234'))


# . (wildcard: any character except newline)
atRegex = re.compile(r'.at')
print(atRegex.findall('The hat on the mat'))

# .* (match whatever)
nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)')
print(nameRegex.findall("First Name: Daniel Last Name: Wagener"))

nongreedy = re.compile(r'<(.*?)>')
print(nongreedy.findall('<To serve humans> for dinner>'))

# re.DOTALL (makes the wildcard match newlines too)
hamlet = "To be or not to be, that is the question \n Whether tis nobler in the mind to suffer \n The slings and arrows of outrageous fortune \n Or to take arms against a sea of troubles \n And by opposing, end them."
dotStar = re.compile(r'.*', re.DOTALL)
print(dotStar.search(hamlet).group())

# Case insensitivity
vowelRegex = re.compile(r'[aeiou]', re.I)
print(vowelRegex.findall(hamlet))
<file_sep>/web-scraping/seleniumScraping.py
from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://automatetheboringstuff.com')
elem = browser.find_element_by_css_selector(
    '.main > ul:nth-child(16) > li:nth-child(1) > a:nth-child(1)')

elem.click()

paragraph = browser.find_element_by_css_selector(
    '#calibre_link-1610 > p:nth-child(5)')

print(paragraph.text)
<file_sep>/flow-control/falsey.py
print("Enter a name.")
name = input()
if name:
    print("Nice work, " + name)
else:
    print("You fail")
<file_sep>/regex/verbose.py
import re

re.compile(r'''
\d\d\d      # Woah, you can add comments inside the regex!
-
\d\d\d
-
\d\d\d\d''', re.VERBOSE)


# Pass multiple options using the bitwise OR operator
re.compile(r'''
\d\d\d      # Woah, you can add comments inside the regex!
-
\d\d\d
-
\d\d\d\d''', re.VERBOSE | re.DOTALL | re.IGNORECASE)
<file_sep>/regex/findall.py
import re

phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')

resume = "My home phone is 123-123-1234, my cell phone is 345-345-3456, and my reference's phone is 567-567-5678. Hire me plz"

print(phoneNumRegex.findall(resume))

# If the regex has two or more groups, the return is a list of tuples
phoneNumRegexWithGroups = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')

print("Behold the tuples:", phoneNumRegexWithGroups.findall(resume))
<file_sep>/excel-word-pdf/editWord.py
import docx
import os

os.chdir('/home/daniel/Downloads')

d = docx.Document('demo4.docx')
# d.add_paragraph('Hello this is a paragraph.')
# d.add_paragraph('This is another paragraph.')

p = d.paragraphs[0]
p.add_run('This is a new run.')
p.runs[1].bold = True

d.save('demo4.docx')
<file_sep>/regex/phoneNumbers.py
import re

message = "Call me 123-123-1234 because that's totes a real phone number. Otherwise, 432-432-4321"

phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')

mo = phoneNumRegex.search(message)
print(mo.group())

print(phoneNumRegex.findall(message))
<file_sep>/regex/sub.py
import re

namesRegex = re.compile(r'Agent \w+')

print(namesRegex.sub(
    'REDACTED', 'Agent Alice gave the secret documents to Agent Bob.'))

# Sub only part of the agents' names
namesRegex2 = re.compile(r'Agent (\w)\w+')
# Here, 1 referes to group 1 defined above
print(namesRegex2.sub(r'Agent \1*****',
                      'Agent Alice gave the secret documents to Agent Bob.'))
<file_sep>/flow-control/if_else_example.py
password = '<PASSWORD>'
if password == '<PASSWORD>':
    print('Access granted')
else:
    print('Wrong password')
<file_sep>/flow-control/if_elif_example.py
name = 'Bob'
age = 1
if name == 'Alice':
    print('Hi Alice')
elif age < 12:
    print('You are not Alice, kiddo')
<file_sep>/gui-automation/screenshot.py
import pyautogui

# Take screenshot
# pyautogui.screenshot('/home/daniel/Pictures/screenshop-example.png')

print(pyautogui.locateAllOnScreen('/home/daniel/Pictures/vs.png'))
<file_sep>/flow-control/fivetimes.py
print('My name is:')
for i in range(10, 0, -2):
    print("Daniel " + str(i))
