[Python] Python script to read multiple excel files in one directory and convert them to .csv...

Discussão em 'Python' iniciado por Stack, Agosto 24, 2025.

  1. Stack

    Stack Membro Participativo

    I am relatively new to python and Stackoverflow but hoping anyone can shed some light of my current problem. I have a python script that takes excel files (.xls, and .xlsx) from one directory and converts them to .csv files to another directory. It works perfectly fine on my sample excel files (consisted of 4 columns and 1 row for the purpose of testing), but when I try to run my script against a different directory that has excel files (alot larger in file size) I am getting an assertion error. I have attached my code and the error. Looking forward to have some guidance on this problem. Thanks!

    import os
    import pandas as pd

    source = "C:/.../TestFolder"
    output = "C:/.../OutputCSV"

    dir_list = os.listdir(source)

    os.chdir(source)

    for i in range(len(dir_list)):
    filename = dir_list
    book = pd.ExcelFile(filename)

    #writing to csv
    if filename.endswith('.xlsx') or filename.endswith('.xls'):
    for i in range(len(book.sheet_names)):
    df = pd.read_excel(book, book.sheet_names)

    os.chdir(output)

    new_name = filename.split('.')[0] + str(book.sheet_names)+'.csv'
    df.to_csv(new_name, index = False)

    os.chdir(source)

    print "New files: ", os.listdir(output)


    [​IMG]

    Continue reading...

Compartilhe esta Página