Phil's Notes

Tagged “python”

  1. Sending Simple Emails with Python 3

  2. To send an email with Python 3, you can use the smtplib and email packages which are already part of the standard library.

    Here’s an example:

    import smtplib
    from email.message import EmailMessage

    # Change these values for your own
    server_address = "mail.yourserver.com"
    port = 25

    message = EmailMessage()
    message["Subject"] = "Test Subject"
    message["From"] = "youremail@yourserver.com"
    message["To"] = "recipient@someplace.com"

    # To include a CC:
    message["CC"] = "ccrecipient@someplace.com"

    # Similarly, to include a BCC:
    message["BCC"] = "bccrecipient@someplace.com"

    message_body = "This is a test message."
    message.set_content(message_body)

    server = smtplib.SMTP(server_address, port)
    server.send_message(message)
    server.quit()

  3. Copying Data From an .xls File to an .xlsx file with Python

  4. Copying spreadsheet data from one spreadsheet to another isn’t very difficult, but if you need to copy data from multiple spreadsheets into one, it can take a while, so why not do it programmatically instead.

    Skip to the end if you want to see the code to copy the data over, otherwise keep reading to see how to use the packages. You can also find the source code here:

    https://github.com/kungfuphil/python-excel-examples

    For this example, you will need to install the xlrd package as well as the openpyxl package. The xlrd package will allow you to read from .xls files, but if you want to write to .xls files, you will also need the xlwt package. We will be writing to an .xlsx file instead, so we will have to install openpyxl.

    Installing the Required Packages

    To install the packages, run these commands in your command line:

    pip install xlrd
    pip install openpyxl

    Reading .xls Files with xlrd

    # This module is to read files with the .xls extension
    from xlrd import open_workbook

    source_spreadsheet_path = "source_spreadsheet.xls"
    source_workbook = open_workbook(source_spreadsheet_path)

    # This is the first worksheet available
    source_worksheet = source_workbook.sheet_by_index(0)

    # Columns in xlrd start at index 0
    source_max_columns = source_worksheet.ncols

    # Rows in xlrd start at index 1
    source_max_rows = source_worksheet.nrows

    # Iterate through the rows of the source file
    for i in range(source_max_rows):
    row = source_worksheet.row_values(i)
    for j, source_cell_value in enumerate(row):
    print(f"[{i},{j}]: {source_cell_value}")

    Or if you want to skip the header row:

    # for i in range(1, source_max_rows):
    row = source_worksheet.row_values(i)
    for j, source_cell_value in enumerate(row):
    print(f"[{i},{j}]: {source_cell_value}")

    Writing to an .xlsx File

    # This module can read and write to files with the .xlsx extension
    from openpyxl import Workbook, load_workbook

    destination_spreadsheet_path = "destination_spreadsheet.xlsx"
    destination_workbook = load_workbook(destination_spreadsheet_path)

    # This is the first worksheet available
    destination_worksheet = destination_workbook.worksheets[0]

    destination_worksheet.cell(row=1, column=1).value = "This is cell A1"
    destination_workbook.save(destination_spreadsheet_path)

    # You don't have to save after every cell. This is just to show
    # that you can continue to append to the same workbook.
    destination_worksheet.cell(row=1, column=2).value = "This is cell B1"
    destination_workbook.save(destination_spreadsheet_path)

    Copying the Data Over

    # This module is to read files with the .xls extension
    from xlrd import open_workbook

    # This module can read and write to files with the .xlsx extension
    from openpyxl import Workbook, load_workbook

    source_spreadsheet_path = "source_spreadsheet.xls"
    source_workbook = open_workbook(source_spreadsheet_path)

    # This is the first worksheet available
    source_worksheet = source_workbook.sheet_by_index(0)

    # Columns in xlrd start at index 0
    source_max_columns = source_worksheet.ncols

    # Rows in xlrd start at index 1
    source_max_rows = source_worksheet.nrows

    destination_spreadsheet_path = "destination_spreadsheet.xlsx"
    destination_workbook = load_workbook(destination_spreadsheet_path)

    destination_worksheet = destination_workbook.worksheets[0]

    # Rows in openpyxl start at index 1, columns also start at index 1
    destination_max_rows = destination_worksheet.max_row

    # If the first cell of the first row is empty, start writing on the first row,
    # otherwise start in the max row count + 1, which should be the next empty row.
    destination_starting_row = 1 if destination_worksheet.cell(1, 1).value is None else destination_max_rows + 1

    # Iterate through the rows of the source file and copy them
    # to the destination file.
    # for i in range(1, source_max_rows): # If you want to skip the header, use this line instead of the next
    for i in range(source_max_rows):
    row = source_worksheet.row_values(i)
    for j, source_cell_value in enumerate(row):
    row_num = destination_starting_row + i
    destination_worksheet.cell(row=row_num, column=j+1).value = source_cell_value

    destination_workbook.save(destination_spreadsheet_path)

  5. Deleting Files in Windows with Python

  6. Here’s a Python script to delete files that are older than 7 days. If you don’t have a lot of files to sort through, it’s possible to do it in the command line with forfiles. However, in my case, I had over 1.6 million files and I wasn’t able to delete them easily using the File Explorer. Using this script still takes time, but at least it won’t freeze up your windows and it will finish eventually. After a day of running the script, the number of files remaining reduced to 1.3 million.

    import os
    import time
    from datetime import datetime

    def main():
    path = r"C:\your\path"
    day_limit = 7
    delete_files_older_than(day_limit, path)

    def delete_files_older_than(days, path):
    delete_age_in_seconds = time.time() - (days * 24 * 60 * 60)
    for entry in os.scandir(path):
    full_path = os.path.join(path, entry.name)
    stat = os.stat(full_path)
    if (stat.st_mtime <= delete_age_in_seconds):
    print(f"Removing {entry.name} from {datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d')}")
    os.remove(full_path)

    if __name__ == '__main__':
    main()

See all tags.