-
-
Save scheckley/9324a043307f03d48ca4dc80d29665c9 to your computer and use it in GitHub Desktop.
modified to convert to csv with corrected utf8 encoding in pandas
This file contains hidden or 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
| # -*- coding: utf-8 -*- | |
| import click | |
| import os | |
| import pandas as pd | |
| def file_split(file): | |
| s = file.split('.') | |
| name = '.'.join(s[:-1]) # get directory name | |
| return name | |
| def getsheets(inputfile, fileformat): | |
| name = file_split(inputfile) | |
| try: | |
| os.makedirs(name) | |
| except: | |
| pass | |
| df1 = pd.ExcelFile(inputfile) | |
| for x in df1.sheet_names: | |
| print(x + '.' + fileformat, 'Done!') | |
| df2 = pd.read_excel(inputfile, sheetname=x) | |
| filename = os.path.join(name, x + '.' + fileformat) | |
| if fileformat == 'csv': | |
| df2.to_csv(filename, index=False,encoding='utf-8-sig') | |
| else: | |
| df2.to_excel(filename, index=False) | |
| print('\nAll Done!') | |
| CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) | |
| @click.command(context_settings=CONTEXT_SETTINGS) | |
| @click.argument('inputfile') | |
| @click.option('-f', '--format', type=click.Choice([ | |
| 'xlsx', 'csv']), default='xlsx', help='Default xlsx.') | |
| def cli(inputfile, format): | |
| '''Convert a Excel file with many sheet to one sheet. | |
| Examples: | |
| \b | |
| get_sheet filename | |
| \b | |
| get_sheet filename -f csv | |
| ''' | |
| if format == 'csv': | |
| getsheets(inputfile, 'csv') | |
| else: | |
| getsheets(inputfile, 'xlsx') | |
| cli() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment