如何用A.txt第1行替换B.txt第230行且保留原有内容?
Fix: Replace Line 230 in B.txt with Line 1 from A.txt (Preserve Other Content)
Let's break down what's going wrong with your current code first, then fix it properly:
What's Wrong With Your Current Code
- Opening
B.txtwith"w"mode immediately erases all existing content—this is why your original B.txt data is gone. lines = inputFile.readlines()[0]grabs only the first line of A.txt as a single string, not a list of lines from B.txt. When you loop overenumerate(lines), you're actually iterating over each character in that single string, not processing B.txt's content at all.- Your logic to find the line with
Trimis disconnected from reading B.txt, so the insertion and writing steps don't affect the right data.
Solution 1: Replace Fixed Line 230
If you know you specifically need to replace the 230th line (not just any line with Trim), use this code. Remember: Python uses 0-indexing, so line 230 is at index 229.
# Read the first line from A.txt (strip only the trailing newline to preserve formatting) with open("A.txt", "r") as a_file: line_from_a = a_file.readline().rstrip('\n') # Read all lines from B.txt into a list (each element is one line, including newline) with open("B.txt", "r") as b_file: b_lines = b_file.readlines() # Check if B.txt has at least 230 lines to avoid index errors if len(b_lines) >= 230: # Replace the 230th line (index 229) and add back the newline b_lines[229] = line_from_a + '\n' else: print("Error: B.txt doesn't have 230 lines!") # Write the modified lines back to B.txt with open("B.txt", "w") as b_file: b_file.writelines(b_lines)
Solution 2: Replace Line Containing "Trim"
If you actually want to replace any line that contains Trim (instead of the fixed 230th line), use this version:
# Read the first line from A.txt, format it with a newline with open("A.txt", "r") as a_file: line_from_a = a_file.readline().rstrip('\n') + '\n' # Read all lines from B.txt with open("B.txt", "r") as b_file: b_lines = b_file.readlines() # Find and replace the line with "Trim" for idx, line in enumerate(b_lines): if 'Trim\n' in line: b_lines[idx] = line_from_a break # Stop searching after the first match (remove this if multiple lines need replacing) # Write the updated content back to B.txt with open("B.txt", "w") as b_file: b_file.writelines(b_lines)
Key Notes
- We use
withstatements for file handling: this automatically closes files after operations, preventing resource leaks and bugs from forgottenclose()calls. readlines()stores B.txt's content as a list of strings, making it easy to modify specific lines without rewriting the entire file manually.- We handle newlines explicitly to keep the file formatting consistent (no extra blank lines or missing line breaks).
内容的提问来源于stack exchange,提问作者jonas hed
相关产品推荐
相关产品推荐

