利用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)
相关推荐
曲幽10 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805115 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞18 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派20 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪1 天前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户0332126663671 天前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫1 天前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派1 天前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风1 天前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic