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

Python使用字典值写入文件出现多余空行问题求助

问题

我正在开发一个课程项目——Python CSV转XML转换器。原本代码用固定的"\n"换行符时,XML输出格式正常;但为了增强可定制性,把所有换行语句改成调用xml_dict字典里的"newline"值(默认值也是"\n")后,输出的XML每个元素后都出现了多余空行。明明值一样,为啥会这样?该怎么修复?

原代码片段(修改前)

def _convert_to_xml(self, in_file, out_file, separator, xml_dict):
    """Converts a .csv to .xml."""
    if separator is None:
        separator = ","

    if xml_dict is None:
        xml_dict = {
            "indent": "  ",
            "newline": "\n",
            "row_tag": "row",
            "col_tag":  "col",
            "table_tag": "table"
        }

    rows = []

    with open(in_file, 'r') as input_file:
        raw_text = input_file.read()
        raw_rows = raw_text.splitlines()
        for raw_row in raw_rows:
            print(raw_row)
            rows.append(raw_row.split(separator))
            print(rows)

    with open(out_file, 'w') as output_file:
        output_file.write(f"<{xml_dict['table_tag']}>")
        output_file.write("\n")
        for row in rows:
            output_file.write(f"{xml_dict['indent']}<{xml_dict['row_tag']}>")
            output_file.write("\n")
            for col in row:
                output_file.write(f"{2*xml_dict['indent']}<{xml_dict['col_tag']}>")
                output_file.write(col)
                output_file.write(f"</{xml_dict['col_tag']}>")
                output_file.write("\n")
            output_file.write(f"{xml_dict['indent']}</{xml_dict['row_tag']}>")
            output_file.write("\n")
        output_file.write(f"</{xml_dict['table_tag']}>")

修改前正常输出

<table>
  <row>
    <col>Robert</col>
    <col>Richman</col>
    <col>Felix</col>
    <col>Alexander</col>
  </row>
  <row>
    <col>Daniela</col>
    <col>Daniel</col>
    <col>Danuta</col>
  </row>
  <row>
    <col>Hier</col>
    <col>Nurzwei</col>
  </row>
  <row>
    <col>eins</col>
  </row>
</table>

修改后异常输出

<table>

  <row>

    <col>Robert</col>

    <col>Richman</col>

    <col>Felix</col>

    <col>Alexander</col>

  </row>

  <row>

    <col>Daniela</col>

    <col>Daniel</col>

    <col>Danuta</col>

  </row>

  <row>

    <col>Hier</col>

    <col>Nurzwei</col>

  </row>

  <row>

    <col>eins</col>

  </row>

</table>

原因分析与修复方案

问题根源

核心问题出在Python文本模式下的换行符自动转换机制:

  • 当用open(out_file, 'w')(默认文本模式)打开文件时,Python会自动将代码中的"\n"转换为当前系统的默认换行符(Windows下是"\r\n",Linux/macOS下是"\n")。
  • 若修改代码后,xml_dict["newline"]的实际值被意外设置为"\r\n"(比如从配置文件读取、或其他代码逻辑篡改),再加上Python的自动转换,会导致写入"\r\r\n",在文本编辑器中显示为多余空行。
  • 即使默认值设为"\n",也可能因函数调用时的参数传递错误,导致newline值被篡改。

修复步骤

方案1:禁用自动换行转换(推荐)

打开输出文件时指定newline='',强制Python原样写入换行符,避免自动转换:

with open(out_file, 'w', newline='') as output_file:

方案2:确保newline值的一致性

  • 检查所有调用_convert_to_xml函数的地方,确认传入的xml_dict中newline值为预期的"\n"(或自定义换行符)。
  • 可在函数开头添加校验逻辑,保证newline是合法的单换行符:
# 在xml_dict初始化后添加
if not isinstance(xml_dict["newline"], str) or len(xml_dict["newline"]) > 2:
    xml_dict["newline"] = "\n"

方案3:统一字符串写入逻辑

将标签与换行符合并成单个字符串写入,减少单独调用write()的次数,避免意外的换行重复:

# 替换原有的多行write为单行逻辑
output_file.write(f"<{xml_dict['table_tag']}>{xml_dict['newline']}")
for row in rows:
    output_file.write(f"{xml_dict['indent']}<{xml_dict['row_tag']}>{xml_dict['newline']}")
    for col in row:
        output_file.write(f"{2*xml_dict['indent']}<{xml_dict['col_tag']}>{col}</{xml_dict['col_tag']}>{xml_dict['newline']}")
    output_file.write(f"{xml_dict['indent']}</{xml_dict['row_tag']}>{xml_dict['newline']}")
output_file.write(f"</{xml_dict['table_tag']}>")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 22:55:58