Python Snippets

a collection of useful snippets

06 Sep 2022

identify if all caps

if all(char.isupper() for char in first):

eg:

if all(char.isupper() for char in first):

    new_first = string.capwords(first, sep=None)

    print(f"{first} ----> {new_first}")

prints:

AMELIE ----> Amelie
JAN ----> Jan
ERIC ----> Eric

capitalise strings

import string

first = 'pierre-GARCIA'

if not first[0].isupper():

    first = first.strip()

    if '-' in first:
        new_first = string.capwords(first, sep='-')
    else:
        new_first = string.capwords(first, sep=None)

    print(f"{first} ----> {new_first}")

# Can be used with separator, ie
# formatted = string.capwords(sentence, sep = 'g')

prints:

pierre-GARCIA ----> Pierre-Garcia
highlights = ['x', 'y', 'z']

for index, value in enumerate(highlights):
    print(index, value)

prints:

0 x
1 y
2 z

for count instead of index:

for index, value in enumerate(highlights):
    print(index + 1, value)
try:
    # write code that may throw exception
except Exception as e:
    # the code for handling the exception
    print(e)

09 Sep 2022

printing to file

easiest method

with open('filename.txt', 'w') as f:
    print('This message will be written to a file.', file=f)

or to append continuously replace w with a:

with open('filename.txt', 'a') as f:
    print('This message will be written to a file.', file=f)

redirecting a Python's script output in the terminal

If script run from Terminal, redirect the output (print) of the script to a file, using a single right angle bracket:

$ python3 hello.py > output.txt

redirecting the Standard Output Stream

to print to file:

original_stdout = sys.stdout # save original stdout

with open('test.txt', 'w') as f:
    sys.stdout = f
    print("TEST")
    sys.stdout = original_stdout # reverts to original stdout

CSV to database with Pandas

check if directory exists

Use os.path.isdir for directories only:

os.path.isdir('new_folder')

Use os.path.exists for both files and directories:

os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))

play the system sound bell

print('\a')

identify if a string is a number

.isdigit()

string = "12345"
if string.isdigit():
    print("The string contains only digits.")
else:
    print("The string does not contain only digits.")

or .isnumeric()

string = "12345"
if string.isnumeric():
    print("The string contains only digits.")
else:
    print("The string does not contain only digits.")

links

social