Created
March 17, 2017 20:34
-
-
Save zooba/1aec8540fe8205937f450ac8cfcc7483 to your computer and use it in GitHub Desktop.
Function for viewing dataframes in Excel (or default CSV viewer)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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