Todd Smith
Todd Smith

Reputation: 1

How to convert XLSX file to CSV with same name as XLSX?

I'm converting a .xlsx file into a data frame and then into a .csv file. The code is writing the CSV file name as 'output.csv'. How can I make the CSV file name be the same as the .xlsx file name in the case that I upload many .xlsx files?

def getExcel ():
    global df

    import_file_path = filedialog.askopenfilename()
    df = pd.read_excel (import_file_path,)
    df.to_csv('output.csv', index=False, header=True)
    print (df)

Upvotes: 0

Views: 216

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54698

Don't use globals. Have the function return the dataframe, and the caller can decide whether to print it or store it.

I used splitext here to handle either .xls or .xlsx.

def getExcel ():
    import_file_path = filedialog.askopenfilename()
    df = pd.read_excel (import_file_path)
    newname = os.path.splitext(import_file_path)[0] + '.csv'
    df.to_csv(newname, index=False, header=True)
    return df

Upvotes: 1

Related Questions