简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM