Search code examples
pythonread-write

Python reads a file to verify user response and fails


I made a program which would make a 12-letter Key and write it to a file. Then the user had to find the Key in the file and type it in and then the program would read the file to verify and it fails to do so.

I tried again but it was still not working. I typed the exact letters of the Key and it didn't work and said "fail". Here is a snippet of the code.

iKey = input("Key: ")

print("validating...")
f = open("./Keys.txt", "r")
Key = f.read()
print(Key)
if iKey == Key:
    print("success!")
else:
    print("fail")

Please bare in mind I am pretty new to Python so I might look over things that you might consider easy to spot.


Solution

  • The thing is that f.read() reads also a newline character in the end. So the pure solution here is to use the strip() to remove any special characters like the new line \n. So Key = f.read().strip() should do the trick.

    Now some other comments. Although python closes its files itself, it's generally a good practice to close the files yourself. Use f.close() in the end of the file.

    And let's now talk about a python's keyword with. The with statement in Python is used to wrap the execution of a block of code with methods defined by a context manager. This is most commonly used for managing resources like file operations, where it ensures that the file is properly closed after its suite finishes, even if an error is raised. This concept is known as "context management" and is part of Python's resource management protocol.

    So, you could write your code as

    iKey = input("Key: ")
    
    print("validating...")
    
    with open("Keys.txt", "r") as f:
      Key = r.read().strip()
    
    print(Key)
    if iKey == Key:
        print("success!")
    else:
        print("fail")
    

    And one last comment that will help you in the future is debugging your code. You can use print statements to figure out why your code isn't working. In this case you could utilize the length of the strings to verify everything is okay like here print(iKey, Key, len(iKey), len(Key))