简体   繁体   中英

Looking for a specific text in .txt file

I am new at Python and for a simple project I tried to make a simple program using .txt file.

A sample text file looks like this:

Name = Garry
Age = 20

Then, I wrote this

Search = input("Whose age do you want to know? ")

    f = open("text exe.txt", "r")
    reviews = f.readlines()
    this_line = reviews[0].split(" = ")
    if this_line[1] == Search:
        print("yes")
    f.close()

When I tried to input "Garry" into Search, "yes" doesn`t come out. Does anyone know the reason? Thank you

Welcome! Comparing strings can be very tricky: this_line[1] contains not only "Garry", but also e line separator "\\r\\n".

Although "Garry" (your input) and "Garry\\r\\n" (from your file) appear the same to us, they are considered different by == operator.

The solution below removes spaces and other non-visible characters around the word, producing the desired output:

Search = input("Whose age do you want to know? ")

f = open("text exe.txt", "r")
reviews = f.readlines()
this_line = reviews[0].split(" = ")
if this_line[1].strip() == Search.strip():
    print("yes")
f.close()

This could solve your problem.

Search = input("Whose age do you want to know? ")
f = open("test.txt", "r")
reviews = f.readlines()
reviews = [x.strip() for x in reviews] 
# print(reviews)
this_line = reviews[0].split(" = ")
if this_line[1] == Search:
    print("yes")
    f.close()

In the txt file the lines are separated with a \\n . If you print this_line it will be ['Name = Gary\\n', 'Age = 20\\n'] . So you should replace the "\\n" with a empty sting. if this_line[1].replace("\\n","") == Search: will work.

Why deal with lists , splits and loops when you can do it this way? You'll deal with that plenty when learning python, in the meantime, here's a nice clean solution:

search = input('Enter:')
f = open("text exe.txt", "r")
if search in f.read():
    print('Yes')
else:
    print('No')
f.close()

Try this

_INPUT_FILE = 'input.txt'

_OUTPUT_FILE = 'output.txt'

def main(): 

pattern = re.compile('^(.*)' +re.escape(sys.argv[1]) + '(.*)$') 

o = open(_OUTPUT_FILE, 'w') 

with open(_INPUT_FILE) as f: 

for line in f: 

match = pattern.match(line) 

if match is not None: 

o.write(match.group(1) + match.group(2) + os.linesep)

o.close() 

if __name__ == '__main__': 

main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM