简体   繁体   中英

Python: How can i search for a whole word in a .txt file?

ive been searching for ages for a solution on my problem: When a user types in a name, which is already saved in a.txt file, it should print "true". If the username is not already existing it should add the name, the user typed in. The Problem is, that it even prints out true when the typed name is "Julia", but "Julian" is already in the list. I hope you get my point. I already read maaany solutions here on stackoverflow but nothing worked for me when working with a.txt file My code:

import mmap
username = input("username: ")
names_file = open("names_file.txt", "a")

paste = bytes(username, 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
     mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
    if s.find(paste) != -1:
        print("true")
    else:
        names_file.write("\n" + username)
        print(username + " got added to the list")



names_file.close()
username = input("username: ")
found = False
with open("names_file.txt", "r") as file:
    for line in file:
        if line.rstrip() == username:
            print("true")
            found = True
            break
if not found:
    with open("names_file.txt", "a") as file:
        file.write( username + "\n")
        print(username + " got added to the list")

You could add the newline after the name and search for the name with the newline character:

import mmap
username = input("username: ")
names_file = open("names_file.txt", "a")

paste = bytes('\n' + username + '\n', 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
    mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
    if s.find(paste) != -1:
        print("true")
    else:
        names_file.write('\n' + username + '\n')
        print(username + " got added to the list")

names_file.close()

This will not work for names with spaces inside -- for such cases you'll have to define different separator (also if all names begin with a capital letter and there are no capital letters in the middle of the name then you could spare the newline before the name)

Try this i have updated my answer.

import mmap
import re
status = False
username = input("username: ")
names_file = open("names_file.txt", "a")

paste = bytes(username, 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
    mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
    for f in file:
        f = f.strip()
        if f == paste:
            print("true")
            status = True
    if status == False:
        names_file.write("\n" + username)
        print(username + " got added to the list")



names_file.close()

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