excel 引擎问题的扩展名无效,正在遍历目录和文件

smdnsysy  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(116)

我有一个代码,如果我手动插入path, directory and file name的字符串,它可以正常工作,下面是代码:

path = r"test//ab3b//ab3b_all_anal.xlsx"
directory = "test"

file1 = "test//ab3b//ab3b80.csv"
df1 = all_calc_80(file1, directory)

file2 = "test//ab3b//ab3b80m.csv"
df2 = all_calc_80m(file2, directory)

writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
df1.to_excel(writer, sheet_name = '80')
df2.to_excel(writer, sheet_name = '80m')
writer.close()

测试目录下有ab3b, bg3a, ge3b等子目录,每个子目录下都有以相同方式命名的文件:ab3b80.csv, ab3b80m.csv; bg3a80.csv, bg3a80m.csv; ge3b80.csv, ge3b80m.csv .
基于80.csv or 80m.csv结尾的每个文件使用不同的函数进行分析。最终输出是一个excel工作簿,工作表名称在csv文件结尾之后。
现在我正在遍历整个目录test,在这里我只需要给予directory的名字,所有的事情都自动从那里开始。

import os
import xlsxwriter
rootdir = 'test'

slovar = {}
for subdir, dirs, files in os.walk(rootdir):
        slovar[subdir] = files
    

for key, value in slovar.items():
    if len(key) > 4:               #to get just subdirectories I need
        end = key[-4:]
        path = 'r' + '\'' + key + '\\\\' + end + '_all_anal.xlsx' + '\''
        print(path)
        
    for vrednost in value:        
        if vrednost.endswith('80.csv'):
            file1 = vrednost
            df1 = all_calc_80(file1, rootdir)

        elif vrednost.endswith('80m.csv'):
            file2 = vrednost
            df2 = all_calc_80m(file2, rootdir)
            
    writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
    df1.to_excel(writer, sheet_name = '80')
    df2.to_excel(writer, sheet_name = '80m')
    writer.close()

但我得到错误消息:Invalid extension for engine '<property object at 0x000002123659D0E0>': 'xlsx'' .
我认为可能会有一些问题,由于/\在窗口路径或对象类型,即使当我打印出来的只是键和值,我得到有用的输出,也正确写入路径的名称。
但我真的不明白为什么手动一切工作和自动化没有。

2w2cym1i

2w2cym1i1#

如果有人还在寻找这个答案,我已经找到了一个解决方案。主要的发现是关于如何将路径和文件名附加到列表中。如果你使用os.walk,它是用os.path.join(dirpath, filename)完成的。
下面是工作代码:

seznam80 = []
seznam80m = []
seznam120 = []
seznam120m = []
seznam150 = []
seznam150m = []
seznamSMT = []
dirp = []

for dirpath, dirnames, filenames in os.walk(directory): #directory with all folders of participants
        for filename in [f for f in filenames if f.endswith("80.csv")]: #search for all 80 files
            seznam80.append(os.path.join(dirpath, filename))
            dirp.append(dirpath)

for dirpath, dirnames, filenames in os.walk(directory): #directory with all folders of participants
        for filename in [f for f in filenames if f.endswith("80m.csv")]: #search for all 80m files
            seznam80m.append(os.path.join(dirpath, filename))

for vsak80, vsak80m pot in zip(seznam80, seznam80m, dirp):
        path = pot + '_all_anal.xlsx'

        file1 = vsak80
        df1 = all_calc_80(file1, directory)

        file2 = vsak80m
        df2 = all_calc_80m(file2, directory)

        writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
        df1.to_excel(writer, sheet_name = '80')
        df2.to_excel(writer, sheet_name = '80m')
        
        writer.close()

相关问题