You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python从数据库生成多行固定宽度文本文件?

生成多行固定宽度文本文件的Python实现

你可以基于现有的FixWidthFieldLine类扩展批量处理逻辑,实现从数据库读取多条记录并生成固定宽度文本文件的功能。以下是优化后的代码:

完整实现代码

class FixWidthFieldLine(object):
    fields = (('foo', 10),
              ('bar', 30),
              ('ooga', 30),
              ('booga', 10))

    def __init__(self, foo='', bar='', ooga='', booga=''):
        # 优化初始化逻辑,支持直接传入字段值
        self.foo = foo
        self.bar = bar
        self.ooga = ooga
        self.booga = booga

    def __str__(self):
        return ''.join([getattr(self, field_name).ljust(width) 
                        for field_name, width in self.fields])

def generate_fixed_width_file(output_path, records):
    """
    批量生成固定宽度文本文件
    :param output_path: 输出文件的路径
    :param records: 待写入的记录列表,元素可以是字典或元组
    """
    with open(output_path, 'w') as file:
        for record in records:
            # 根据记录类型创建格式化行实例
            if isinstance(record, dict):
                line = FixWidthFieldLine(**record)
            else:
                # 元组需遵循(foo, bar, ooga, booga)的顺序
                line = FixWidthFieldLine(*record)
            file.write(f"{line}\n")

# 模拟从数据库获取的多条数据(实际场景替换为数据库查询结果)
sample_db_records = [
    {'foo': 'hi', 'bar': 'joe', 'ooga': 'howya', 'booga': 'doin?'},
    {'foo': 'abc', 'bar': 'def', 'ooga': 'ghi', 'booga': 'jkl'},
    {'foo': 'test1', 'bar': 'long text example here', 'ooga': 'another long string', 'booga': 'end1'},
    ('test2', 'short bar', 'medium ooga', 'end2')
]

# 生成文本文件
generate_fixed_width_file('fixed_width_output.txt', sample_db_records)

针对大型数据库的优化方案

如果处理的是超大规模数据库数据,建议采用分批读取的方式,避免一次性加载所有数据占用过多内存:

def fetch_db_records_batch(conn, batch_size=1000):
    """分批从数据库读取记录的示例函数"""
    cursor = conn.cursor()
    cursor.execute("SELECT foo, bar, ooga, booga FROM your_target_table")
    
    while True:
        batch = cursor.fetchmany(batch_size)
        if not batch:
            break
        yield batch

# 使用示例(需替换为实际数据库连接逻辑)
# import mysql.connector  # 以MySQL为例
# db_conn = mysql.connector.connect(
#     host="localhost",
#     user="your_user",
#     password="your_pwd",
#     database="your_db"
# )

# with open('large_fixed_width.txt', 'w') as out_file:
#     for record_batch in fetch_db_records_batch(db_conn):
#         for record in record_batch:
#             line = FixWidthFieldLine(*record)
#             out_file.write(f"{line}\n")

# db_conn.close()

关键说明

  • 优化了FixWidthFieldLine的初始化方法,支持直接传入字段值,简化赋值操作
  • generate_fixed_width_file函数负责批量处理记录并写入文件,使用上下文管理器确保文件安全关闭
  • 支持字典和元组两种记录格式,适配不同的数据库查询返回结果
  • 分批读取方案适合处理超大量数据,降低内存占用

内容的提问来源于stack exchange,提问作者Nayana Mahajan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 22:21:37