i have in folder 13 csv files named 1,2,3 13 (1.csv,2.csv,3csv , on), , want convert them single excel file(xlsx) organized in sheets starting 1 until 13 in numerical order! , used this:
import glob, csv, xlwt, os wb = xlwt.workbook() filename in glob.glob("data/*.csv"): (f_path, f_name) = os.path.split(filename) (f_short_name, f_extension) = os.path.splitext(f_name) ws = wb.add_sheet(f_short_name) spamreader = csv.reader(open(filename, 'r')) rowx, row in enumerate(spamreader): colx, value in enumerate(row): ws.write(rowx, colx, value) wb.save("compiled.xlsx")
my problem output: compiled.xlsx won't have sheets in order want (starting 1,2,3,4,5 ...13), start 4,13,11,12,5,6,8 , so. have files in folder in desired order, how can change code in order proper sheet ordering, i'm using python 3, time!
you can sort csv files filename list , use list instead.
i made assumption filenames can converted int
type.
files = [os.path.split(filename) filename in glob.glob("csvs/*.csv")] ordered_files = sorted( files, key=lambda x: int(os.path.splitext(x[1])[0]) ) wb = xlwt.workbook() f_path, f_name in ordered_files: (f_short_name, f_extension) = os.path.splitext(f_name) ws = wb.add_sheet(f_short_name) spamreader = csv.reader(open(os.path.join(f_path, f_name), 'r')) rowx, row in enumerate(spamreader): colx, value in enumerate(row): ws.write(rowx, colx, value) wb.save("compiled.xlsx")
Comments
Post a Comment