利用Python将文件夹下多个txt文本写入到同一个excel中(每一个文件占一行)

1、 将文件夹下多个txt文本写入到同一个excel中(每一个文件占一行):

python 复制代码
# -*- coding: utf-8 -*-
import os
import pandas as pd

# 获取文件夹中的所有txt文件
folder_path = r'G:\Cygwin\'
txt_files = [f for f in os.listdir(folder_path) if f.endswith('.txt')]

# 创建一个空的DataFrame用于存储数据
merged_data = pd.DataFrame()

# 逐个读取txt文件并将内容转换为一行存储到DataFrame中
for file in txt_files:
    file_path = os.path.join(folder_path, file)
    with open(file_path, 'r') as f:
        content = f.read().replace('\n', '')
        data = pd.DataFrame([content.split('\t')])
        merged_data = pd.concat([merged_data, data], ignore_index=True)


# 将合并后的数据保存到Excel文件中
output_file = r'G:\Cygwin\output.xlsx'
merged_data.to_excel(output_file, index=False, header=False)

2、将文件夹下多个EXCEL文本写入到同一个excel中不同的sheet:

python 复制代码
import os
import pandas as pd

# 设置文件夹路径
folder_path = r'G:\Cygwin\SBDART-master1\TestRuns\2000'

# 获取文件夹中所有 Excel 文件的文件名
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx')]

# 创建一个 ExcelWriter
with pd.ExcelWriter(r'G:\Cygwin\SBDART-master1\TestRuns\2000\2000.xlsx') as writer:
    # 遍历每个 Excel 文件并将数据写入到不同 sheet 中
    for file in excel_files:
        df = pd.read_excel(os.path.join(folder_path, file))
        sheet_name = os.path.splitext(file)[0]  # 使用文件名作为 sheet 名称
        df.to_excel(writer, sheet_name=sheet_name, index=False)
相关推荐
碳酸的唐2 小时前
A* 工程实践全指南:从启发式设计到可视化与性能优化
python·神经网络
曾令胜3 小时前
excel导出使用arthas动态追踪方法调用耗时后性能优化的过程
spring·性能优化·excel
执尺量北斗5 小时前
[特殊字符] 基于 Qt + OpenGL 实现的入门级打砖块游戏
开发语言·qt·游戏
夏子曦5 小时前
C#内存管理深度解析:从栈堆原理到高性能编程实践
开发语言·c#
倔强青铜三5 小时前
苦练Python第64天:从零掌握多线程,threading模块全面指南
人工智能·python·面试
我命由我123456 小时前
Excel - Excel 列出一列中所有不重复数据
经验分享·学习·职场和发展·word·powerpoint·excel·职场发展
Q26433650237 小时前
【有源码】基于Hadoop生态的大数据共享单车数据分析与可视化平台-基于Python与大数据的共享单车多维度数据分析可视化系统
大数据·hadoop·python·机器学习·数据分析·spark·毕业设计
jiajixi7 小时前
Go 异步编程
开发语言·后端·golang
QX_hao7 小时前
【Go】--strings包
开发语言·后端·golang