使用Python中的模式匹配将xlsx转换为csv不起作用

4si2a6ki  于 2023-05-26  发布在  Python
关注(0)|答案(1)|浏览(116)

目录中有几个xlsx文件。但我想搜索xlsx文件与文件名20230406115500.001.A0.XZI.INVOICING_ES101_Anlage_DISCO_Split_20230405_114751.xlsx
我想搜索上面的文件与模式匹配的东西像*ES101*.xlsx,然后将此xlsx文件转换为csv。只有一个文件具有此文件名模式。下面是Python代码:

import pandas as pd

read_file = pd.read_excel (r'/home/repo/"*ES101*.xlsx"')')
read_file.to_csv (r'/home/repo/ES101.csv', index = None, header=True)

但它会抛出错误No such file or directory。我在Linux服务器上运行这个Python代码。我用的是Python3.9版本。

piztneat

piztneat1#

你可以使用glob函数搜索,然后读取文件:

from glob import glob

# it searches all the files containing the pattern, in this case I take the first and only one
file_name = glob('/home/repo/*ES101*.xlsx')[0]

dataframe = pd.read_excel(file_name, sheet_name='sheet_name')
dataframe.to_csv("file_name.csv", index=False)

# if you want the same name for the file you just can
dataframe.to_csv(file_name.split('.')[0]+'.csv', index=False)

您需要安装xlsxwriter引擎。

相关问题