Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 仅当数组包含特定工作表时,才将目录中的所有excel文件追加到数组中_Python_Excel_Pandas_Append - Fatal编程技术网

Python 仅当数组包含特定工作表时,才将目录中的所有excel文件追加到数组中

Python 仅当数组包含特定工作表时,才将目录中的所有excel文件追加到数组中,python,excel,pandas,append,Python,Excel,Pandas,Append,目前,我正在读取所有excel文件,并将“数据”表附加到给定目录中的数组中。问题是目录中的一些excel文件实际上不应该存在,并且不包含“数据”表。一旦遇到这种情况,程序就会中断。我的解决方法是在添加文件之前打印文件名,然后手动删除文件并重新运行脚本。我尝试创建一个Sheet_check函数,如下所示,尽管这大大降低了运行时间,也没有达到预期效果 Q:如果有一种简单/有效的方法,仅在特定工作表存在的情况下添加excel文件 read_files = glob.glob(os.path.join(

目前,我正在读取所有excel文件,并将“数据”表附加到给定目录中的数组中。问题是目录中的一些excel文件实际上不应该存在,并且不包含“数据”表。一旦遇到这种情况,程序就会中断。我的解决方法是在添加文件之前打印文件名,然后手动删除文件并重新运行脚本。我尝试创建一个Sheet_check函数,如下所示,尽管这大大降低了运行时间,也没有达到预期效果

Q:如果有一种简单/有效的方法,仅在特定工作表存在的情况下添加excel文件

read_files = glob.glob(os.path.join(file_path, "*.xlsx"))

file_array = []
for files in read_files:
    #Remove_password_xlsx(files, password)

    #if Sheet_check(files) == False:
        #read_files.remove(files)

    print(files)
    data = pd.read_excel(files, 'Data')
    file_array.append(data)
不起作用:

def Sheet_check(filename):
    bAvailable = False
    book = load_workbook(filename)
    sheets = book.sheetnames
    for sheet in sheets:
        if sheet.upper() == "DATA":
            bAvailable = True
            break
    return bAvailable

使用异常应该有效:

from xlrd import XLRDError
read_files = glob.glob(os.path.join(file_path, "*.xlsx"))

file_array = []
for files in read_files:
    #Remove_password_xlsx(files, password)

    #if Sheet_check(files) == False:
        #read_files.remove(files)

    print(files)
    try:
        data = pd.read_excel(files, sheet_name='Data')
        file_array.append(data)
    except XLRDError:
        print('No "Data" sheet')

谢谢修复它现在可以工作了!多谢各位