Search code examples
pythonexcelpython-3.xcsvxlwt

Python convert csv files to a ordered excel sheet


I have in my folder 13 csv files that are named 1,2,3 to 13 (1.csv,2.csv,3csv and so on), and I want to convert them to a single excel file(xlsx) organized in sheets starting to 1 up until 13 but in a numerical order! And for that I used this:

import glob, csv, xlwt, os
wb = xlwt.Workbook()
for 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'))
    for rowx, row in enumerate(spamReader):
        for colx, value in enumerate(row):
            ws.write(rowx, colx, value)
wb.save("compiled.xlsx")

My only problem is that my output: compiled.xlsx won't have the sheets in the order I want (starting from 1,2,3,4,5 ...13), it will start with 4,13,11,12,5,6,8 and so. I have the files in my folder in the desired order, how I can change my code in order to get a proper sheet ordering, I'm using python 3, thanks for your time!


Solution

  • You can sort csv files by filename into a list and use that list instead.

    I made an assumption that all filenames can be converted to int type.

    files = [os.path.split(filename) for filename in glob.glob("csvs/*.csv")]
    ordered_files = sorted(
        files, key=lambda x: int(os.path.splitext(x[1])[0])
    )
    
    
    wb = xlwt.Workbook()
    for 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'))
        for rowx, row in enumerate(spamReader):
            for colx, value in enumerate(row):
                ws.write(rowx, colx, value)
    wb.save("compiled.xlsx")