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 beitems(your dictionary is nameditems, notitem)Results[1]→ this should besplitStuff[1]since you split the line into thesplitStuffvariable
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 usingwithstatements—they automatically handle closing files safely, even if an error occurs. - The
len(splitStuff) >= 2check 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 thanreadlines(), which is helpful for large files.
内容的提问来源于stack exchange,提问作者cybera

