Python Code Snippets

Below are some useful Python code snippets for use in everyday projects.

When dealing with directories and files it may be necessary to check for their existence. Below is an example of how to do this.

import os

# Example path and file.
exampletPath = 'C:\\demo\\'
exampleFile = 'example.txt'

# Check if the path exists.
if os.path.exists(exampletPath):

    print(f"The path '{exampletPath}' exists.")

else

    print(f"The path '{exampletPath}' doesn't exists.")

# Check if the file exists.
if os.path.isfile(exampleFile):

    print(f"The file '{exampletPath}{exampleFile}' exists.")

else

    print(f"The file '{exampletPath}{exampleFile}' doesn't exists.")

Python can be used to copy and move files.

import shutil

# Example paths and files.
exampletPathSource = 'C:\\demo\\'
exampletPathDestination = 'C:\\demo\\backup\\'
exampleFile1 = 'example1.txt'
exampleFile2 = 'example2.txt'

# Copy the example1.txt file.
shutil.copyfile(exampletPathSource + exampleFile1, exampletPathDestination + exampleFile1)

# Move the example2.txt file.
shutil.move(exampletPathSource + exampleFile2, exampletPathDestination + exampleFile2)

Here is an example of how to generate a random number between two values, in this case 1 and 59, then display it.

import random

# Minimum and maximum values for random number.
min_val = 1
max_val = 59

# Generate random number.
random_number = random.randint(min_val, max_val)

# Display the number in the console/terminal.
print(random_number)

Here, a random password is generated from a specified set of characters. The length of the password is also randomly selected from a given minimum and maximum length.

import random

# Possible characters in password.
alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
numbers = '0123456789'
nonAlpha = '{]+-[*=@:)}$^%;(_!&#?>/|.'

# Combine possible password characters into one string.
charSet = alpha + numbers + nonAlpha

# Minimum and maximum password length.
minLength = 20
maxLength = 30

# Select a random password length between the minimum and maximum.
length = random.randint(minLength, maxLength)

# Variable for new password.
result = ""

# Construct new password.
for num in range(0, length):

    # Add a randomly selected character to the new password.
    result += charSet[random.randint(0, len(charSet)-1)]

# Display the password.
print(result)

When handling a number of files, it can sometimes be useful to compress them in to one file. Python can be used to both create and extract from a zip archive.

import shutil

# Example paths and files.
exampletPathSource = 'C:\\demo\\'
exampletPathDestination = 'C:\\demo2\\'
examplePathZip = 'C:\\temp\\demo'  # Exclude extension from file name.
exampleFileFormat = 'zip'

# Create the zip archive file.
shutil.make_archive(examplePathZip, exampleFileFormat, exampletPathSource)

# Extract the zip archive file.
shutil.unpack_archive(f"{examplePathZip}.{exampleFileFormat}",
                      exampletPathDestination, exampleFileFormat)