利用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)
相关推荐
李白同学19 分钟前
【C语言】结构体内存对齐问题
c语言·开发语言
黑子哥呢?2 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash
失败尽常态5232 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447742 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农2 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿2 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Leuanghing2 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
彳卸风3 小时前
Unable to parse timestamp value: “20250220135445“, expected format is
开发语言
dorabighead3 小时前
JavaScript 高级程序设计 读书笔记(第三章)
开发语言·javascript·ecmascript
xinxiyinhe3 小时前
如何设置Cursor中.cursorrules文件
人工智能·python