首页 > 解决方案 > 读取和写入 xlsx 文件,从 pandas 数据帧到特定目录

问题描述

我在python中有一个函数,它基本上将三个txt文件合并为一个文件,格式为xlsx。为此,我使用 pandas 包。所以我在某个目录中运行python函数。此函数将输入作为特定路径。然后函数取这个路径,列出目录的文件,过滤需要的文件。这意味着,由于我只想读取 txt 文件,因此我过滤了 txt 文件。但是,当我尝试将此 txt 文件转换为熊猫数据框时,数据框为无。另外,我想将最终的 xlsx 写入初始文件所在的目录。这是我的功能:

def concat_files(path):
    summary=''
    files_separate=[]
    arr2 = os.listdir(mypath)
    for i, items_list in enumerate(arr2):
        if len(items_list) > 50:
            files_separate.append(items_list)
    files_separate
    chunks= [files_separate[x:x+3] for x in range(0,len(files_separate),3)]
    while chunks:
        focus=chunks.pop(0)
        for items_1 in focus:
            if items_1.endswith('.Cox1.fastq.fasta.usearch_cluster_fast.fasta.reps.fasta.blastn.report.txt.all_together.txt'):
                pandas_dataframe=pd.Dataframe(example)
                pandas_dataframe.to_excel('destiny_path/' + str(header_file)+'.final.xlsx')

标签: python-3.xpandaswindows

解决方案


您需要在导出 xlsx 文件之前创建文件夹。所以假设您已经创建了文件夹。

更改此行

pandas_dataframe.to_excel('destiny_path/' + str(header_file)+'.final.xlsx')

pandas_dataframe.to_excel(os.path.join('destiny_path' ,str(header_file),'.final.xlsx'))

推荐阅读