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

Python写入SQL查询结果到文本文件时如何移除末尾多余空行

末尾空行移除方案

出现多余空行的原因是print()函数默认会在输出内容末尾追加换行符\n,遍历到最后一行查询结果时也会新增换行,最终导致文件末尾多出空行。你可以选择以下任意一种方案解决:

  • 方案1:小数据量场景下,统一拼接后写入
    先把所有查询结果收集到列表,用\n拼接后一次性写入,只会在行与行之间插入换行,末尾不会生成多余空行:
cursor.execute(sql_p11)
# 收集所有查询结果
result_list = [str(row[0]) for row in cursor]
# 路径前加r避免Windows路径反斜杠转义问题,指定encoding避免乱码
with open(r'D:\Automate\Output\out.txt', 'w', encoding='utf-8') as myFile:
    myFile.write('\n'.join(result_list))
  • 方案2:大数据量场景下,逐行控制换行符
    如果查询结果量极大,不适合全部载入内存,可以单独控制每一行的结束符:
cursor.execute(sql_p11)
row_iter = iter(cursor)
with open(r'D:\Automate\Output\out.txt', 'w', encoding='utf-8') as myFile:
    try:
        # 第一行不追加末尾换行
        first = next(row_iter)
        print(first[0], file=myFile, end='')
        # 后续行先加换行再输出内容
        for row in row_iter:
            print(f'\n{row[0]}', file=myFile, end='')
    except StopIteration:
        # 查询结果为空时无操作
        pass
  • 方案3:不改原有写入逻辑,写完后截断末尾换行
    如果不想调整原有循环写入的代码,可以在写完后判断末尾字符,直接截断多余换行:
import os
cursor.execute(sql_p11)
file_path = r'D:\Automate\Output\out.txt'
with open(file_path, 'w', encoding='utf-8') as myFile:
    for row in cursor:
        print(row[0], file=myFile)

# 截断末尾换行
if os.path.getsize(file_path) > 0:
    with open(file_path, 'rb+') as f:
        f.seek(-1, os.SEEK_END)
        if f.read(1) == b'\n':
            f.truncate()

内容的提问来源于stack exchange,提问作者Mariam Mehdi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:18:02