Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Search text in file and print all text

okay. you didnt understand anything from the title. let me explain.

now ı have a file. There is some text in this file. for example "jack.123 jackie.321"

I want to check if the word jack exists in the file and ı wanna print "jack.123".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

its my problem. ı didnt print all text.

def append(name,password):
  f = open("myfile.txt", "w")
  f.write("{},{}".format(name,password))

append("jack",".123")
append("jackie" , ".321")
f = open("myfile.txt" ,"r")
if "jack" in f.read():
    print("query found")

>Solution :

Open the file and read all its contents then split on whitespace. That effectively gives you all the words in the file.

Iterate over the list of words checking to see if a word starts with the name you’re searching for followed by ‘.’.

Note that there may be more than one occurrence so build a list.

def find_name(filename, name):
    if not name[-1] == '.':
        name += '.'
    found = []
    with open(filename) as myfile:
        for word in myfile.read().split():
            if word.startswith(name):
                found.append(word)
    return found

print(*find_name('myfile.txt', 'jack'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading