修改address.txt手机号时else语句重复打印问题求助
Got it, the issue here is that your current code is likely checking each line in address.txt and printing the error message every time a line doesn't match the old phone number. That's why you see it 3 times for 3 records—one for each non-matching line!
Here's a straightforward fix using a flag variable to track whether we found the number at all, so we only print the error once after checking every line:
def editContact(): # Flag to track if we found the target phone number number_found = False output = [] option = raw_input("Enter 1 for edit email id and Enter 2 for edit phone number : ") if option == "2": old_number = raw_input("Enter old phone number to edit: ") new_number = raw_input("Enter new phone number: ") # Read all lines from the file with auto-close with open("address.txt", "r") as file: for line in file: if old_number in line: # Replace the old number and mark as found updated_line = line.replace(old_number, new_number) output.append(updated_line) number_found = True else: # Keep the line as-is if no match output.append(line) # Write the updated content back to the file with open("address.txt", "w") as file: file.writelines(output) # Only print the error message once, after checking all lines if not number_found: print("Mobile number not found") elif option == "1": # Apply the same fix for email editing to avoid duplicate errors email_found = False old_email = raw_input("Enter old email id: ") new_email = raw_input("Enter new email id: ") with open("address.txt", "r") as file: for line in file: if old_email in line: updated_line = line.replace(old_email, new_email) output.append(updated_line) email_found = True else: output.append(line) with open("address.txt", "w") as file: file.writelines(output) if not email_found: print("Email id not found") else: print("Invalid option selected")
What Changed & Why:
- Added boolean flags:
number_found(andemail_foundfor the other option) starts asFalse. We only set it toTruewhen we actually find a line matching the old number/email. - Moved error checking to post-iteration: Instead of printing the error during each non-matching line, we wait until we've checked every record. If the flag stays
False, we know the number wasn't present—so we print the error once. - Used
withstatements: This is a bonus for cleaner file handling—it automatically closes the file when we're done, eliminating the risk of forgottenclose()calls.
If your address book lines follow a strict format (like Name: Alice, Phone: 1234567890), you could make the matching more precise (e.g., check for exact phone field matches) to avoid accidental replacements. But the core fix for duplicate error messages is the flag variable approach.
内容的提问来源于stack exchange,提问作者deepak rawat

