Skip to content

Instantly share code, notes, and snippets.

@LanternD
Last active December 12, 2020 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LanternD/7722f0f839b161f7734ded606c33e8ec to your computer and use it in GitHub Desktop.
Save LanternD/7722f0f839b161f7734ded606c33e8ec to your computer and use it in GitHub Desktop.
Collection of handful Python short snippets.
"""Useful short snippets in Python."""
# Return the list of all the file names in the given directory
import os
def get_file_list(file_path):
files = []
for root, dirs, files in os.walk(file_path):
print('# of files: {0}'.format(len(files))) # can be "pass"
file_list = files
return file_list
# Create/delete a directory with 755 permission
import os
path = "/tmp/year"
access_rights = 0o755
## Create
try:
os.mkdir(path, access_rights)
except OSError:
print ("Creation of the directory %s failed" % path)
else:
print ("Successfully created the directory %s" % path)
## Delete
try:
os.rmdir(path)
except OSError:
print ("Deletion of the directory %s failed" % path)
else:
print ("Successfully deleted the directory %s" % path)
# Check whether a file or folder exists:
import os
os.path.isfile('./file.txt') # file only
os.path.isdir('./dir') # directory only
os.path.exists('./file.txt') # file or directory
# Skip header of csv
import csv
with open("in.csv", "rb") as f_csv:
reader = csv.reader(f_csv)
next(reader, None) # skip the headers
# Get the current time (as file name timestamp)
import time
timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime((time.time())))
print(timestamp)
# To get the current working directory use
import os
cwd = os.getcwd()
# Get the name/OS/platform
import os
os.name
import platform
platform.system()
platform.release()
# Truncate the matplotlib color map
import matplotlib as mpl
from matplotlib import pyplot as plt
import numpy as np
def truncate_cmap(cmap, minval=0.0, maxval=1.0, n=100): # n is the granularity
new_cmap = colors.LinearSegmentedColormap.from_list(
"trunc({n},{a:.2f},{b:.2f})".format(n=cmap.name, a=minval, b=maxval),
cmap(np.linspace(minval, maxval, n)),
)
return new_cmap
new_blues = truncate_cmap(plt.get_cmap("Greens"), 0.4, 0.8, n=100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment