簡體   English   中英

將多個 .xls 文件轉換為 .csv python

[英]Convert multiple .xls files into .csv python

我需要將很多文件從 .xls 轉換為 .csv 文件。 我嘗試使用循環來制作它:

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)

我得到了錯誤:

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

哪些變量以及如何更改?

為此使用pathlib 特別是, pathlib.Path.with_suffix()方法提供了一種更改文件擴展名的簡單方法。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM