Instantly share code, notes, and snippets.

View simple_logging.py
import logging
import logging.handlers
logger = logging.getLogger()
# handler = logging.handlers.WatchedFileHandler(path_log)
handler = logging.handlers.StreamHandler()
# formatter = logging.Formatter(logging.BASIC_FORMAT)
formatter = logging.Formatter('{levelname}:{message}', style='{')
handler.setFormatter(formatter)
logger.addHandler(handler)
View pytest_tmpdir_factory.py
import json
import os
import pytest as pt
# See Python Testing with pytest. > Chapter 4 > Using tmpdir and tmpdir_factory
class TestStuff(object):
@pt.fixture(scope='class')
View universal_directory.py
import os
import pathlib
# 1
# -------------------------------------------------
os.environ["ALLUSERSPROFILE"]
# The environment variable "ALLUSERSPROFILE" is available on Windows only.
# On Windows returns
# 'C:\\ProgramData'
View filename_pattern_matching.py
import fnmatch
pattern = "aaa_*" # Special characters '*' and '?'
list_of_all_files = ['aaa_1.json', 'a.json', 'b.json']
for filename in list_of_all_files:
if fnmatch.fnmatch(filename, pattern):
print(filename)
View get_filename_from_path.py
# See
# https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format
import ntpath
path_to_file = r"C:\a\b\s\d\f_a\aasdas_o_g.json"
print(ntpath.basename(path_to_file)
# Output:
View files_in_directory.py
# See
# https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
View current_time_with_pendulum.py
import pendulum
now = pendulum.now()
now.format('YYYYMMDD_HHmm')