简体   繁体   中英

I'm trying to get my program to create a file which will save an input, but I don't want it to appear twice. (Python)

The code I am using is:

i=0
f= open("username list.txt", "a+")
for i in range(i+1):
    user=input("Enter your Pokémon Go username to continue.")
    if user != i:
        f.write(user)
    print("Welcome,", user)
f.close()

and when the file gets made and appended, if the input is the same, ie "hello", it saves again in the file, like this:

hellohello

which I don't want to happen. I thought I should do some kind of verification for whether or not the input is already in the file, and ask the user whether they want to put their name into the file. What should I do??

PS: I would also like the different names to be seperated, either by a new line or a comma.

The most basic and easiest way to do this is to open it in read mode to begin with, separate them through lines and do a basic if x in y iteration to see if its already there.

Example:

with open("username list.txt", "r") as usernames:
    username_list = usernames.read().splitlines() # .readlines() doesn't always work in my experience, but you're welcome to try it.

i=0
with open("username list.txt", "a+") as f
    for i in range(i+1):
        user=input("Enter your Pokémon Go username to continue.")
        if user != i and user not in username_list:
            f.write(user+"\n") # Make sure you add the new line here otherwise the system wont work.
        print("Welcome,", user)

With using this, make sure that username list.txt is rather reset/deleted before using or manually put the usernames are on new lines.

The most basic way to do this would be to read the file manually before writing the name and check for a duplicate name before writing the code.

You will need to use seek .

i= 10
f= open("username_list.txt", "a+")
for i in range(i+1):
    f.seek(0)
    duplicate_found = False
    user=input("Enter your Pokémon Go username to continue.")
    if user != i:
        for name in f:
            if user == name[:-1]:
                duplicate_found = True
                break;
        if not duplicate_found:
            f.write(user+"\n")
    print("Welcome,", user)
f.close()

Or instead, you can optimize your program by also keeping the information in memory with collections like dict .

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