读取文件每行并追加字符串写入输出文件时异常,求解决
Hey there! Let's work through why your string-adding logic is only behaving correctly for the last few lines—this is such a common gotcha, so we’ll get it sorted quickly.
1. You’re Reusing a Variable Without Resetting It
If you’re using one string variable to build every line and don’t clear it between loop iterations, earlier lines might get merged or overwritten by later ones. Here’s what that broken code might look like:
# Bad: Reusing the same variable across loops line_content = "" with open("source.txt", "r") as src, open("output.txt", "w") as out: for line in src: line_content += line.strip() + " YOUR_SUFFIX\n" out.write(line_content)
Each loop appends to line_content, so every write includes all previous lines. Fix it by creating a fresh variable for each line:
# Good: New variable for every line with open("source.txt", "r") as src, open("output.txt", "w") as out: for line in src: modified_line = line.strip() + " YOUR_SUFFIX\n" out.write(modified_line)
2. Opening the Output File Inside the Loop
If you open the output file in w mode inside your loop, you’ll overwrite the entire file every single time you run the loop—only the last write will stay. Like this:
# Bad: Overwriting the output file on every iteration with open("source.txt", "r") as src: for line in src: modified_line = line.strip() + " YOUR_SUFFIX\n" with open("output.txt", "w") as out: # This wipes the file each time! out.write(modified_line)
Fix this by opening the output file once before the loop (use w to create/overwrite, or a if you need to add to an existing file):
# Good: Open output file once, write all lines to it with open("source.txt", "r") as src, open("output.txt", "w") as out: for line in src: modified_line = line.strip() + " YOUR_SUFFIX\n" out.write(modified_line)
3. Not Flushing the Output Buffer
Some languages (like Python) buffer file writes for efficiency. If your program exits before the buffer is flushed, some lines might never get written to the file. You can either:
- Call
flush()after each write (great for debugging, though not the most performant):out.write(modified_line) out.flush() - Or just rely on the
withstatement—it automatically flushes and closes the file when the block ends, which is the recommended approach.
4. Trailing Whitespace/NewLine Issues
If your source file has inconsistent line endings, stripping them incorrectly might cause weird behavior. Try preserving the original line breaks while adding your suffix:
# Preserve original line endings with open("source.txt", "r") as src, open("output.txt", "w") as out: for line in src: # Remove only the trailing newline, add suffix, then restore it modified_line = line.rstrip("\n") + " YOUR_SUFFIX\n" out.write(modified_line)
If none of these fixes work, share a snippet of your actual code and we can dig into the specifics!
内容的提问来源于stack exchange,提问作者ProTechXS

