JSON to csv string in python

Posted on Updated on

from cStringIO import StringIO
import csv

def json_to_csv(data):
    output = StringIO()
    writer = csv.DictWriter(output, data[0].keys())
    for row in data:
    return output

print (write_csv([{"name": "Dolor", "age": "23"}, {"name": "John Doe", "age": "32"}, {"age": "42", "name": "Lorem Ipsum"}], 'output.csv').getvalue())

# output
# age,name
# 23,Abiral
# 32,Lorem
# 42,asdfasd

Find max and min number from a number having the same number of digits as that number

Posted on Updated on

foo_number = 12345
min = pow(10, len(str(foo_number)) - 1) # 10000
max = pow(10, len(str(foo_number))) - 1 # 99999

Python extract filename and extension from filepath

Posted on Updated on

import os
inputFilepath = 'path/to/file/foobar.txt'
filename_w_ext = os.path.basename(inputFilepath)
filename, file_extension = os.path.splitext(filename_w_ext)
#filename = foobar
#file_extension = .txt

path, filename = os.path.split(path/to/file/foobar.txt)
# path = path/to/file
# filename = foobar.txt

Python Selenium Webdriver selectors

Posted on Updated on

from selenium import webdriver # import webdriver
browser = webdriver.Chrome() # initiate chrome browser for instance
browser.find_element_by_id('id of element to select') # return first element matched by the selector
browser.find_elements_by_id('id of element to select) # returns list of all elements matched by the selector
browser.find_element_by_xpath('selector expression')
browser.find_element_by_link_text('selector expression')
browser.find_element_by_partial_link_text('selector expression')
browser.find_element_by_name('selector expression')
browser.find_element_by_tag_name('selector expression')
browser.find_element_by_class_name('selector expression')
browser.find_element_by_css_selector('selector expression')

The function names are self explanatory. Every function has the element(s) version to return list of elements matched by the selector