百万行数据文件拆分成多个新文件

39 阅读1分钟

在工作,我们经常遇到一种情况,

老板直接丢给你10万行 txt数据,  让你使用.

可是我发现, 这个文件太大了,打开会很久.

所以,我写了个小程序, 这样就可以把10万行数据, 自动创建新文件,每个新文件 存10000行数据

这样就ok了

import pandas as pd
import os

def txt_to_excel(txt_file_path, excel_file_path):
    """
    将txt文件中的数据导入到Excel文件中
    """
    try:
        # 检查txt文件是否存在
        if not os.path.exists(txt_file_path):
            print(f"错误:文件 {txt_file_path} 不存在")
            return False
        
        # 读取txt文件
        with open(txt_file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
        
        # 解析数据
        data = []
        for line in lines:
            line = line.strip()  # 去除首尾空白字符
            if line:  # 跳过空行
                # 使用 '----' 分割每行数据
                parts = line.split('----')
                data.append(parts)
        
        # 创建DataFrame
        # 假设每行有6列数据(根据你提供的数据格式)
        df = pd.DataFrame(data)
        
        # 设置列名(根据你的数据格式调整)
        if len(df.columns) == 6:
            df.columns = ['Email1', 'Password', 'UUID', 'Token', 'Email2', 'Code']
        
        # 保存为Excel文件
        df.to_excel(excel_file_path, index=False)
        
        print(f"成功将数据导入到 {excel_file_path}")
        print(f"共处理 {len(data)} 行数据")
        return True
        
    except Exception as e:
        print(f"处理过程中出现错误: {e}")
        return False

# 使用示例
if __name__ == "__main__":
    # 输入文件路径
    txt_file = "test.txt"   
    
    # 输出文件路径
    excel_file = "output_data.xlsx"  # 或者使用 .xls
    
    # 执行转换
    txt_to_excel(txt_file, excel_file)
    
    
    

今天是我第一次用掘金, 还有些不好意思, 之前都是用的云笔记.