晚安,斯塔克
我面临一个与Python上的pandas库相关的问题。我正在尝试在多个excel文件(具有多个工作表)上自动执行批量追加/合并。但是,我不知道如何简单地跳过不包含特定工作表名称的文件。有什么想法吗?我的代码如下:
PS1:当代码读取每个xlsx文件中的每一页时,我必须插入一个中断来结束迭代
PS2:错误是:“XLRDError:没有名为<;'CSNSC 2020'>;”的工作表
PS3:我找到了一种方法:在循环之后放置一个try,然后为错误设置一个异常。但是,对于这一点,我需要在代码的其余部分正常工作时保持整洁
import pandas as pd
import os
path = r'C:/Users/Thiago/Desktop/Backup/Python/Files test append xlsx'
files = os.listdir(path)
df = pd.DataFrame()
xlsx_files = [path + '\\' + f for f in files if f[-4:] == 'xlsx']
for i in xlsx_files:
xlsx = pd.ExcelFile(i)
for name in xlsx.sheet_names:
data = pd.read_excel(i, header = 1, sheet_name = "CSNSC 2020")
data['File'] = i
print(i)
df = df.append(data)
break
df = df[['Dt. Ref.','Convênio','Tipo de Atendimento','Venc.']]
df.head()
df = df.dropna(subset=['Convênio'])
df.head()
df.to_excel(r'C:/Users/Thiago/Desktop/Backup/Python/Files test append xlsx/out.xlsx')
谢谢
我编写了这个简单的函数来处理excel文件,并处理缺少工作表的excel文件。您可以根据自己的用例随意调整它
需要注意的主要问题是
try
和except
来处理错误模块
行动中
功能
相关问题 更多 >
编程相关推荐