简体   繁体   中英

Convert multiple .xls files into .csv python

I need to convert a lot of files from .xls to .csv files. I tried to use loop to make it:

excel_files = glob.glob("A/2018/*xls")

for excel in excel_files:
    out = excel.split('.')+'.csv'
    df = pd.read_excel(excel)
    df.to_csv(out)

And i got error:

TypeError                                 Traceback (most recent call last)
<ipython-input-62-a04c590b0fd7> in <module>
      1 for excel in excel_files:
----> 2     out = excel.split('.')+'.csv'
      3     df = pd.read_excel(excel)
      4     df.to_csv(out)

TypeError: can only concatenate list (not "str") to list

Which variables and how I can change?

Use pathlib for this. In particular, the pathlib.Path.with_suffix() method provides a simple way of changing the file extension.

from pathlib import Path
import pandas as pd

excel_files = Path("A/2018").glob("*xls")

for excel_file in excel_files:
    df = pd.read_excel(excel_file)
    out_path = excel_file.with_suffix(".csv")
    df.to_csv(out_path)

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