Search text in file and print all text

Question:

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")
Asked By: Hasan Cb

||

Answers:

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

Answered By: Webinator06

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'))
Answered By: Cobra
def new_pass(name, passwd):
    "creates file and write name and passwd to it"
    with open("myfile1.txt", "a") as f:
        f.write(name + "." + passwd + "n")


new_pass("jack", "123")
new_pass("jack", "183")
new_pass("jack", "129")
new_pass("jack", "223")


def check_word(file, word):
    """checks if a word exists and returns its first occurence """
    with open(file) as f:
        l = f.read().split("n")
    for i in l:
        if i.startswith(word):
            print("query found")
            return i


print(check_word("myfile1.txt", "jack"))
Answered By: inemeawaji
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.