i have a file file.txt i want to search a data in a file using phone number for example if i entered 996452544 then result will be Alex 996452544 alex#gmail how to do that in python i do not know i am newbie help me.
file.txt
Alex 996452544 alex#gmail
Jhon 885546694 jhon#gmail
Arya 896756885 arya#gmail
code.py
def searchContact():
number=raw_input("Enter phone number to search data : ")
obj1=open("file.txt","r")
re=obj1.read()
print re
obj1.close()
searchContact()
def searchContact():
obj1 = open("address.txt","r")
number = raw_input("Enter phone number to search data : ")
for line in obj1.readlines():
if number in line:
print line
obj1.close()
hope this help. If yes accept and upvote
def searchContact():
number=raw_input("Enter phone number to search data : ")
obj1=open("file.txt","r")
re=obj1.read()
print re
x= re.split("\n")
matching = [s for s in x if number in s]
print matching
obj1.close()
searchContact()
This simple code will do the work
def searchContact():
number=raw_input("Enter phone number to search data : ")
obj1=open("file.txt","r")
for line in obj1.readlines():
if number in line:
print(line)
obj1.close()
I hope this will help you
for line in obj1.readlines():
if number in line:
print line
Related
access next index in loop
I've got a text file containing the following lines:
what's you'r name?
my name is Micheal
how old are you?
I'm 33 year's old
filename= input("file name?\n")
try:
txt = open(filename+'.txt', 'r', encoding='utf-8').readlines()
print('could not find file name')
except FileNotFoundError:
print('could not fine file')
for count, line in enumerate(txt):
pass
for i in range(count+1):
print('Q',txt[i])
print('A',txt[i+1])
Text file contain question and answer, i try to make the output like:
question
answer
question
answer
like as it is in text file.
You can use a for-loop with a step:
for i in range(0,len(txt),2):
print('Q',txt[i])
print('A',txt[i+1])
you should use step inside range function.
something like this
for i in range(0,count+1, 2):
print('Q',txt[i])
print('A',txt[i+1])
range(startFrom, endWith, step)
Another way: store the question and answer data in different list and then use range.
txt = '''what's you'r name?
my name is Micheal
how old are you?
I'm 33 year's old'''
data = txt.split('\n')
ques = data[0::2]
ans = data[1::2]
for i in range(len(ques)):
print(f'Question:{ques[i]}')
print(f'Answer:{ans[i]}')
>>> Question:what's you'r name?
Answer:my name is Micheal
Question:how old are you?
Answer:I'm 33 year's old
I am a newbie. I failed one of the test cases in a phone book problem. As per the question, a user is expected to enter a single line input which contains a name (which can be one or more words) followed by a number. I have to split the the input into ["name","number"] and store it in dictionary. Note that the name will have one or more words(Eg: John Conor Jr. or Apollo Creed). I am confused with the splitting part. I tried out the split() function and re.split(). Not sure I can solve this.
Sample input 1 : david james 93930000
Sample Input 2 : hshhs kskssk sshs 99383000
Output: num = {"david james" : "93930000", "hshhs kskssk sshs" : "99383000"}
I need to store it in a dictionary where the key:value is "david james": "93930000"
Please help. Thank you
=====>I found a solution<==========
if __name__ == '__main__':
N=int(input())
phonebook={}
(*name,num) = input().split()
name = ''.join(map(str,name)
phonebook.update({name:num})
print(phonebook)
The astrik method words. But for a large data set this might slow me down. Not sure.
So im assuming that the inputs stated are coming from a user, if that
is the case you could change the format in your code to something
similar to this. You can change the range depending on how many inputs you want.
name = {}
for i in range(5):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
name[student_name.title()] = student_mark
print(marks)
This should print the results in the way you mentioned!
Please check for the updated answer if this is what you are looking
for.
# Sample text in a line...
# With a name surname and number
txt = "Tamer Jar 9000"
# We define a dictionary variable
name_dictionary = {}
# We make a list inorder to appened the name and surname to the list
name_with_surname = []
# We split the text and if we print it out it should look something like this
# "Tamer", "Jar", "9000"
# But you need the name and surname together so we do that below
x = txt.split()
# We take the first value of the split text which is "Tamer"
# And we take the second value of the split text us "Jar"
name = x[0]
surname = x[1]
# And here we append them to our list
name_with_surname.append(name + " " + surname)
#print(name_with_surname)
# Finally here to display the values in a dictionary format
# We take the value of the list which is "Tamer Jar" and the value of the number "9000"
name_dictionary[name_with_surname[0]] = x[2]
print(name_dictionary)
The above answers can't handle if a data has too many name parts in one line.
Try my code below.
You can just loop through whatever the total number of inputs you want.
phonebook = {}
total_inputs = int(input())
for i in range(total_inputs):
name_marks = input().split() # taking input and splitting them by spaces
name = " ".join(x for x in name_marks[:-1]) # extracting the name
marks = name_marks[-1] # extracting the marks
phonebook[name] = marks # storing the marks in the dictionary
This way you can store the marks for the name. It will handle even one input has many name parts.
I'm trying to read a large number of user inputs line by line instead of by spacing.
code:
keyword = (input("\n Please enter the keywords "))
keywords = keyword.split(" ")
words:
a
abandon
ability
able
abortion
The input function ends by pressing enter or moving to a new line, so you have to define how you want to finish instead.
If you're looking for a way to enter 5 words like you did in your example, this should be enough:
print("\n Please enter the keywords ")
keywords = [input() for i in range(5)]
You can change range(5) to range(3000) or any other number that you wish.
If you would like in input an infinite amount of words until some special keyword is entered (like "quit") you can do this:
print("\n Please enter the keywords ")
keywords = []
while True:
k = input()
if k == 'quit':
break
else:
keywords.append(k)
You may want to read from the sys.stdin, for example:
import sys
it = iter(sys.stdin)
while True:
print(next(it))
Here you have a live example
I am new to python and have trouble with my homework. I want to read a file from a location and look for how many times a number appears in that file. I have done where you read the file and get the list. I also used linear search in the program to look for the number. However, no matter what I do I will get the answer of the number is no in the list. Can anyone help me out here?
Here is my code:
import os.path
fLocation="C://TEMP//"
print("Assumed file location is at: ", fLocation)
fName = input("\nPlease enter a file name with its extension (ex. XXX.txt): ")
try:
fin = open(fLocation + fName, 'r')
aStr = fin.read()
aList = aStr.split()
def linearSearch(intList,target):
found=False
position=0
while position<len(intList):
if intList[position] == target:
found=True
break
position=position+1
return found
mynum=int(input("What is the number you are looking for in the file?"))
filenum= linearSearch(aList, mynum)
if filenum:
print("The number is in index: ",aList)
else:
print("The number is not in the list")
You are getting wrong answer because you're comparing string with an int
Your intList is a list of string and not int.You are parsing mynum to int while taking input. Remove the int parsing and your string will match.
mynum=input("What is the number you are looking for in the file?")
Also, if you are expecting print("The number is in index: ",aList) will print the indexes at which string is matched, then you'll not get correct output as it displaying the input list and not the list with indexes.
I am trying to write a function that will allow the user to enter a name or phone number, check if it is present in a file, and if it is prints out the entire line in which that element has been found. I have so far:
def searchPlayer():
with open("players.txt") as f:
data = f.readlines()
print "Enter 0 to go back"
nameSearch = str(raw_input("Enter player surname, forname, email, or phone number: "))
if any(nameSearch in s for s in data):
#Finding the element in the list works
#Can't think of a way to print the entire line with the player's information
else:
print nameSearch + " was not found in the database"
The file is formatted like so:
Joe;Bloggs;j.bloggs#anemailaddress.com;0719451625
Sarah;Brown;s.brown#anemailaddress.com;0749154184
So if nameSearch == Joe, the output should be Joe;Bloggs;j.bloggs#anemailaddress.com;0719451625
Any help would be appreciated, thank you
Why not use a loop?
for s in data:
if nameSearch in s:
print s
break
any is looping anyway, from the docs:
def any(iterable):
for element in iterable:
if element:
return True
return False
Seems too complicated, just do
with open("players.txt") as f:
for line in f:
if nameSearch in line:
print line
You can't use any as others have mentioned, but you can use next if you want to keep the more compact code. Instead of:
if any(nameSearch in s for s in data):
you'd use next with a default value:
entry = next((s for s in data if nameSearch in s), None)
if entry is not None:
print entry,
else:
print nameSearch, "was not found in the database"
Note: You might want to use csv.reader or the like to parse here, as otherwise you end up mistaking formatting for data; if a user enters ; you'll blindly return the first record, even though the ; was formatting, not field data. Similarly, a search for Jon would find the first person named Jon or Jonathan or any other name that might exist that begins with Jon.
As #alexis mentioned in a comment, you shouldn't use any() if you want to know which line matched. In this case, you should use a loop instead:
found = False
for s in data:
if nameSearch in s:
print s
found = True
#break # Optional. Put this in if you want to print only the first match.
if not found:
print "{} was not found in the database".format(nameSearch)
If you want to print only the first match, take out the hash sign before break and change if not found: to else:.