Python实现手机号检索文件联系人求助(新手向)
How to Search Contacts by Phone Number in Python
Hey there! I see you're trying to search for a contact using their phone number from your file.txt—let's get that working step by step.
The Problem with Your Current Code
Right now, your code reads the entire file and prints it out, but it doesn't check for the specific phone number you input. We need to add logic to scan each line and match the number you're looking for.
Updated Code
Here's a modified version that does exactly what you need:
def searchContact(): # Get the phone number from user input (use input() instead of raw_input() for Python 3) number = raw_input("Enter phone number to search data : ") # Open the file in read mode (using 'with' auto-closes the file for you) with open("file.txt", "r") as obj1: # Iterate over each line in the file for line in obj1: # Clean up the line and split into contact details contact_details = line.strip().split() # Check if the phone number part matches your input if len(contact_details) >= 2 and contact_details[1] == number: print(line.strip()) break else: # Runs if no matching number was found in any line print(f"No contact found with phone number {number}") searchContact()
Key Changes Explained
- Using
withfor file handling: This is a safer, cleaner way to work with files—it automatically closes the file once we're done, so you don't have to remember to callobj1.close(). - Line-by-line iteration: Instead of loading the whole file at once, we check each line individually. This is more efficient, especially if your contact list grows later.
- Splitting contact details:
line.strip().split()removes extra spaces/newlines and turns each line into a list (like["Alex", "996452544", "alex@gmail"]), making it easy to grab the phone number. - Match check: We target the second item in the split list (since your phone number is always the second entry) and compare it to your input.
- No-match feedback: The
elseblock attached to theforloop runs only if we finish all lines without finding a match, so you get a clear message when the number isn't in the file.
Quick Note for Python 3 Users
If you're running Python 3, just replace raw_input() with input()—that's the only tweak you need!
Now when you run this and enter 996452544, you'll get exactly the result you want: Alex 996452544 alex@gmail. 😊
内容的提问来源于stack exchange,提问作者Vijay
相关产品推荐
相关产品推荐

