Skip to content

Instantly share code, notes, and snippets.

@zooba
Created March 17, 2017 20:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zooba/1aec8540fe8205937f450ac8cfcc7483 to your computer and use it in GitHub Desktop.
Save zooba/1aec8540fe8205937f450ac8cfcc7483 to your computer and use it in GitHub Desktop.
Function for viewing dataframes in Excel (or default CSV viewer)
print('Loaded dataframe viewer script.')
def xl(data, filename='temp.csv'):
import os, tempfile
filename = os.path.join(tempfile.gettempdir(), filename)
try:
# Try and get the to_csv() function
data_to_csv = data.to_csv
except AttributeError:
# No to_csv() function, so assume we have a dict of lists
import csv, itertools
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
keys = list(data)
writer.writerow([''] + keys)
for row in zip(itertools.count(), *(data[k] for k in keys)):
writer.writerow(row)
else:
# Call the to_csv() function we just got
data_to_csv(filename)
# Open the csv file with the default editor
os.startfile(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment