python 将多个txt写入一个Excel中

将多个txt写入Excel
在output文件夹下有多个TXT文件,每个TXT文件有10行,现将所有txt内容写入excel中。

一个txt内容如下:
在这里插入图片描述在excel中的结果如下:
在这里插入图片描述
代码如下:

import xlrd
import os
from xlutils.copy import copy

class Solution:
    def __init__(self):
        self.row = 0
        self.col = 0

    def read_from_txt(self, txt_filename):
        file_txt = open(txt_filename)
        lines = file_txt.readlines()
        self.name = txt_filename.split(os.path.sep)[-1].split('.')[0]
        self.lines = list(map(float,lines))
        print(self.name)
        print(self.lines)


    def write_to_excel(self, excel_filename):
        wb = xlrd.open_workbook(excel_filename)
        xwb = copy(wb)
        # 新建工作簿
        sheet = xwb.get_sheet(0)
        # 如果对同一单元格重复操作会发生overwrite Exception,cell_overwrite_ok为可覆盖
        # 添加工作表
        sheet.write(self.row, self.col, self.name)
        self.row += 1
        for data in self.lines:
            sheet.write(self.row, self.col, data)
            self.row += 1
        self.row = 0
        self.col += 1

        xwb.save(excel_filename)
        # print('save')

if __name__ == '__main__':
    dir = "output"
    zidir = os.listdir(dir)
    new_zidir = []
    for zi in zidir:
        if zi.endswith(".txt"):
            new_zidir.append(zi)

    s = Solution()
    for filename in new_zidir:
        txt_filename =os.path.join(dir,str(filename))
        excel_filename = ".xls"
        s.read_from_txt(txt_filename)
        s.write_to_excel(excel_filename)

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用Python的os和pandas库来将文件夹下的多个txt文件数据写入Excel文件。 首先,需要使用os库的listdir函数获取文件夹下所有的txt文件,如下所示: ``` import os folder_path = 'folder_path' txt_files = [f for f in os.listdir(folder_path) if f.endswith('.txt')] ``` 上述代码,folder_path是文件夹的路径,通过listdir函数获取文件夹下所有的文件名,然后使用列表推导式过滤出所有以'.txt'结尾的文件。 接下来,需要将每个txt文件读取为一个pandas的DataFrame对象,并将这些对象合并成一个DataFrame对象。可以使用pandas的concat函数来实现,如下所示: ``` import pandas as pd df_list = [] for txt_file in txt_files: df = pd.read_csv(os.path.join(folder_path, txt_file), delimiter='\t') df_list.append(df) df = pd.concat(df_list, ignore_index=True) ``` 上述代码,首先定义了一个空的DataFrame对象列表df_list,然后使用for循环遍历所有的txt文件,将每个文件读取为一个DataFrame对象,并将这些对象添加到df_list。最后,使用concat函数将df_list的所有DataFrame对象合并成一个DataFrame对象。 最后,将合并后的DataFrame对象写入Excel文件,可以使用pandas的to_excel函数,如下所示: ``` df.to_excel('output.xlsx', index=False) ``` 上述代码,to_excel函数的第一个参数是输出文件的路径,第二个参数index指定了是否输出行索引。 完整代码示例: ``` import os import pandas as pd # 获取txt文件列表 folder_path = 'folder_path' txt_files = [f for f in os.listdir(folder_path) if f.endswith('.txt')] # 读取文本数据并合并 df_list = [] for txt_file in txt_files: df = pd.read_csv(os.path.join(folder_path, txt_file), delimiter='\t') df_list.append(df) df = pd.concat(df_list, ignore_index=True) # 写入Excel文件 df.to_excel('output.xlsx', index=False) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值