【问题标题】:Convert multiple .xls files into .csv python将多个 .xls 文件转换为 .csv python
【发布时间】:2020-12-30 00:19:31
【问题描述】:

我需要将很多文件从 .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

哪些变量以及如何更改?

【问题讨论】:

  • .split返回一个列表,如果要获取文件名,应该使用excel.split('.')[0]+'.csv'

标签: python csv type-conversion xls


【解决方案1】:

为此使用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)

【讨论】:

  • 嘿,谢谢您的回复,但这种方法对我也不起作用。这次我有错误:TypeError: cannot parse from 'PosixPath'
  • 这个错误在哪里?您可能必须使用pd.read_excel(str(excel_file))df.to_csv(str(out_path))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
  • 2015-11-11
  • 2017-11-30
  • 2011-10-05
  • 2020-01-22
  • 2015-02-02
相关资源
最近更新 更多