5 Advanced Python scripts to Automate like a Pro!

5 Advanced Python scripts to Automate like a Pro!

These are life hacks!

Photo by luciano de sa on Unsplash

1. Homework Automation Script

This script doesn’t complete your homework but is somewhat close enough. It is a Google search for you mentioned in the docx file.

from docx import Document
from googlesearch import search

filename = "PythonQuestions.docx"
questions = []
def getText(filename):
    doc = Document(filename)
    fullText = []
    for para in doc.paragraphs:
        questions.append(para.text)
        fullText.append(para.text)
    return '\n'.join(fullText)

doc = Document()
doc.add_heading('Homework', 0)

for i in questions:
    doc.add_heading(i, level = 1)
    for j in search(i, # query
        lang="en",
        num=5, # number of results
        start=0, # start page
        stop=2, # stop page
        pause=2): # delay between each call
        doc.add_paragraph(j)

doc.save('Homework.docx')

Libraries used in the above script:

pip install python-docx pip install googlesearch-python

2. Files Management Automation Script

I came across this idea during my ever online classes, since I had to download multiple files for multiple subjects and then manually bifurcate them into subject-wise folders it became a tedious task.

Thanks to a StackOverflow answer I found out about the watchdog library for tracking the changes in the directory.

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
import time
import re
import shutil

regexSearch = "Util.py$" # replace your regex here

class MyHandler(FileSystemEventHandler):

    def on_modified(self, event):
        for filename in os.listdir(folder_to_track):
            if(re.search(regexSearch, filename)):
                src = folder_to_track + "\\" + filename
                new_destination = folder_destination + "\\" + filename
                shutil.move(src, new_destination)

folder_to_track = "" # Source
folder_destination = "" # Destination

event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, folder_to_track, recursive = True)
observer.start()

try:
    while True:
        time.sleep(2)
except KeyboardInterrupt:
    observer.stop()

observer.join()

Libraries to download

pip install watchdog

3. Make AudioBook at the fly

If you are someone who looks forward to listening to audiobooks then you surely want this script that would convert all text in a PDF to an MP3 file.

from PyPDF2 import PdfFileReader
from pyttsx3 import init

def getTextFromAllPages():
    txt = ""
    with open('PythonQuestions.pdf', 'rb') as f:
        pdfReaderObj = PdfFileReader(f)
        numPages = pdfReaderObj.getNumPages()
        for pageN in range(numPages):
            page = pdfReaderObj.getPage(pageN)
            pageContent = page.extractText()
            txt += pageContent
    return txt

txt = getTextFromAllPages()
engine = init()
engine.save_to_file(txt, 'test.mp3')
engine.runAndWait()

Libraries to download

pip install PyPDF2 pip install pyttsx3

4. Bulk File Rename Automation Script

This script is a must for all programmers :P

We just badly name a file when bulk downloading files from the internet and then forget to rename them, well look no further this script can save you hours of renaming files.

import os

root = os.path.join('..', 'test')

targetName = "textFile"
iter = 1

for directory, subDirList, fileList in os.walk(root):
    for name in fileList:
        sourceName = os.path.join(directory, name)
        modName = os.path.join(directory, f'{targetName} {iter}')
        iter += 1
        print(f'Changed from: {sourceName} to {modName}')
        os.rename(sourceName, modName)

5. Local Backup Automation Script

This script lets you back up your folders and files in a zip ready to be saved on the cloud.

from zipfile import ZipFile
from os import path, walk

def zipFiles(root):
    zipName = ''.join(path.basename(root) + '.zip')
    backupZipFile = ZipFile(zipName, 'w')
    print(f'Creating {zipName}')
    for directory, subDirList, fileList in walk(root):
        print(f'Adding files in {directory}')
        backupZipFile.write(directory)
        for name in fileList:
            backupZipFile.write(path.join(directory, name))
    backupZipFile.close()
    print('Done!')

root = path.join('..', 'test')
zipFiles(root)

Did you find this article valuable?

Support Rahul's Tech Blog by becoming a sponsor. Any amount is appreciated!