Skip to content

Instantly share code, notes, and snippets.

@adamharder
Last active February 6, 2018 16:28
Show Gist options
  • Select an option

  • Save adamharder/c385abfcd35a39f057b56de9ddd3f6e1 to your computer and use it in GitHub Desktop.

Select an option

Save adamharder/c385abfcd35a39f057b56de9ddd3f6e1 to your computer and use it in GitHub Desktop.

Python 3 Pathlib

https://medium.com/@ageitgey/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f

from pathlib import Path
data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"
print(file_to_open.read_text())


filename = Path("source_data/text_files/raw_data.txt")
print(filename.name)
# prints "raw_data.txt"
print(filename.suffix)
# prints "txt"
print(filename.stem)
# prints "raw_data"
if not filename.exists():
    print("Oops, file doesn't exist!")
else:
    print("Yay, the file exists!")

from pathlib import Path, PureWindowsPath
filename = Path("source_data/text_files/raw_data.txt")
# Convert path to Windows format
path_on_windows = PureWindowsPath(filename)
print(path_on_windows)
# prints "source_data\text_files\raw_data.txt"

List comprehension

z=[x for x in range(100) if x % 3 == 0 ]

Serve a directory on localhost:8000

cd into the directory
python -m SimpleHTTPServer

Print line number:

from inspect import currentframe, getframeinfo

print getframeinfo(currentframe()).filename
print getframeinfo(currentframe()).lineno

read from Stdin

import fileinput
for line in fileinput.input():
    print line

chmod a generated file:

os.chmod("gen_xxx.txt", 0777)
with open(“gen_xxx.txt", "w") as f:
    f.write(“blah blah")
os.chmod("gen_xxx.txt", 0444 )

read a file

with open('filename.txt') as fp:
    for line in fp:

    print line

remove all empty lines in a list of strings:

lines=open(“list_of_stuff.txt").read().split("\n")
print len(lines)
lines=[line for line in lines if len(line.strip())>0]
print len(lines)

do something to each item in a list

elements = ['%{0}%'.format(element) for element in elements]

YAML config files

import yaml
config = yaml.safe_load(open("config.yml"))

frontendurl = config["frontendurl"]
apiurl = config["apiurl"]


config.yaml
__________________
frontendurl : http://xyz.local:8883
apiurl      : http://xyz.local:8080
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment