利用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)
相关推荐
qq_206901398 分钟前
如何使用C#调用Oracle存储过程_OracleCommand配置CommandType.StoredProcedure
jvm·数据库·python
m0_7488394916 分钟前
CSS如何实现元素平滑滚动_使用scroll-behavior属性设置
jvm·数据库·python
Victoria.a30 分钟前
python基础语法
开发语言·python
xiaotao1311 小时前
01-编程基础与数学基石: Python核心数据结构完全指南
数据结构·人工智能·windows·python
青苔猿猿1 小时前
【1】JupyterLab安装
python·jupyter
xiaoyaohou111 小时前
023、数据增强改进(二):自适应数据增强与AutoAugment策略
开发语言·python
鬼圣1 小时前
Python 上下文管理器
开发语言·python
星空椰1 小时前
JavaScript 基础进阶:分支、循环与数组实战总结
开发语言·javascript·ecmascript
yong99902 小时前
IHAOAVOA:天鹰优化算法与非洲秃鹫优化算法的混合算法(Matlab实现)
开发语言·算法·matlab
努力学习_小白2 小时前
ResNet-50——pytorch版
人工智能·pytorch·python