Home > Mobile >  Search text in file and print all text
Search text in file and print all text

Time:12-06

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".

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")

CodePudding user response:

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'))

CodePudding user response:

In python you can do it like that :

with open('file.txt', 'r') as file:
    data = file.read()

if "jack" in data:
    print("jack")

If I understood uncorrectly let me know

  • Related