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

Python修改字典值后为何频繁出现换行?新手技术求助

Hey there! Let's break down what's going on here and fix those unexpected newlines. 😊

First, Fix the Obvious Typos in Your Code

You've got a couple of variable name mistakes that would throw errors before even hitting the newline issue:

  • if splitStuff[0] in item: → should be items (your dictionary is named items, not item)
  • Results[1] → this should be splitStuff[1] since you split the line into the splitStuff variable

The Root Cause of Unexpected Newlines

When you use content = f.readlines(), every line in the resulting list includes the trailing newline character \n from the original file. For example, if a line in your file is 3!Angel\n, splitting it with split('!') gives you splitStuff[1] = "Angel\n"—the newline is still attached. When you write this value back to the file, that \n automatically creates a new line.

Even if your original file has multiple entries on a single line, any trailing newline from the line itself will carry through and cause unexpected line breaks in the output.

How to Fix It

Here's the adjusted code with fixes for both typos and the newline problem:

items = dict()
with open(path) as f:
    # Iterate directly over the file object (more memory-efficient than readlines())
    for line in f:
        # Remove trailing newline characters before processing
        line_clean = line.rstrip('\n')
        splitStuff = line_clean.split('!')
        # Add a check to avoid index errors if a line lacks the ! separator
        if len(splitStuff) >= 2:
            key = splitStuff[0]
            value = splitStuff[1]
            if key in items:
                items[key] += ',' + value
            else:
                items[key] = value

with open(path2, 'a') as f:
    for key, value in items.items():
        # Explicitly control newlines: add \n if you want each entry on its own line, omit if not
        f.write(f"{key}!{value}\n")

Extra Tips

  • You don't need to call f.close() when using with statements—they automatically handle closing files safely, even if an error occurs.
  • The len(splitStuff) >= 2 check prevents crashes if any line in your input file doesn't have the ! separator.
  • Iterating directly over the file object (for line in f) uses less memory than readlines(), which is helpful for large files.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:05:38