I'm trying to make a simple log in menu. The database is stored locally via .txt file, but there is an error in finding a path to it

Question:

I’m very new to python, so as one of the first projects I decided to a simple log-in menu, however, it gives me a mistake shown at the bottom.

The link to the tutorial I used:

https://www.youtube.com/watch?v=dR_cDapPWyY&ab_channel=techWithId

This is the code to the log-in menu:

def welcome():
    print("Welcome to your dashboard")

def gainAccess(Username=None, Password=None):
    Username = input("Enter your username:")
    Password = input("Enter your Password:")
    
    if not len(Username or Password) < 1:
        if True:
            db = open("database.txt", "C:UsersDeePakOneDriveDesktopdatabase.txt.txt")
            d = []
            f = []
            for i in db:
                a,b = i.split(",")
                b = b.strip()
                c = a,b
                d.append(a)
                f.append(b)
                data = dict(zip(d, f))
            try:
                if Username in data:
                    hashed = data[Username].strip('b')
                    hashed = hashed.replace("'", "")
                    hashed = hashed.encode('utf-8')
                    
                    try:
                        if bcrypt.checkpw(Password.encode(), hashed):
                        
                            print("Login success!")
                            print("Hi", Username)
                            welcome()
                        else:
                            print("Wrong password")
                        
                    except:
                        print("Incorrect passwords or username")
                else:
                    print("Username doesn't exist")
            except:
                print("Password or username doesn't exist")
        else:
            print("Error logging into the system")
            
    else:
        print("Please attempt login again")
        gainAccess()
        
        # b = b.strip()
# accessDb()

def register(Username=None, Password1=None, Password2=None):
    Username = input("Enter a username:")
    Password1 = input("Create password:")
    Password2 = input("Confirm Password:")
    db = open("database.txt", "C:UsersDeePakOneDriveDesktopNamedatabase.txt")
    d = []
    for i in db:
        a,b = i.split(",")
        b = b.strip()
        c = a,b
        d.append(a)
    if not len(Password1)<=8:
        db = open("database.txt", "C:UsersDeePakOneDriveDesktopNamedatabase.txt")
        if not Username ==None:
            if len(Username) <1:
                print("Please provide a username")
                register()
            elif Username in d:
                print("Username exists")
                register()      
            else:
                if Password1 == Password2:
                    Password1 = Password1.encode('utf-8')
                    Password1 = bcrypt.hashpw(Password1, bcrypt.gensalt())
                                       
                    db = open("database.txt", "C:UsersDeePakOneDriveDesktopNamedatabase.txt")
                    db.write(Username+", "+str(Password1)+"n")
                    print("User created successfully!")
                    print("Please login to proceed:")

                    
                    # print(texts)
                else:
                    print("Passwords do not match")
                    register()
    else:
        print("Password too short")



def home(option=None):
    print("Welcome, please select an option")
    option = input("Login | Signup:")
    if option == "Login":
        gainAccess()
    elif option == "Signup":
        register()
    else:
        print("Please enter a valid parameter, this is case-sensitive")




# register(Username, Password1, Password2)
# gainAccess(Username, Password1)
home()

When I run it, I get this issue:

    db = open("database.txt", "C:UsersDeePakOneDriveDesktopNamedatabase.txt")
                                                                                                        ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape
Asked By: NeoWeb

||

Answers:

Four ideas on how to fix your code:

  1. Pass only one file to the open function, since that is what it expects.
  2. Open the file in ‘w’ mode since you are writing to it.
  3. Open the file with utf-8 encoding since you may be writing unicode characters to it.
  4. Pass the filepath as a raw string literal by prefixing it with r.

After applying all these changes, this line of code:

db = open("database.txt", "C:UsersDeePakOneDriveDesktopNamedatabase.txt")

Should instead look like this:

db = open(r"C:UsersDeePakOneDriveDesktopNamedatabase.txt", 'w', encoding='utf-8')
Answered By: Brent Pappas

Use

r"C:UsersDeePakOneDriveDesktopdatabase.txt.txt"

Explanation in String and Bytes literals (slightly reformated):

Escape sequences only recognized in Python string literals are:

Escape Sequence Meaning
ooo            Character with octal value ooo (up to three octal digits)
xnn            Character with  8-bit hex value nn
unnnn          Character with 16-bit hex value nnnn
Unnnnnnnn      Character with 32-bit hex value nnnnnnnn
N{name}        Character named name in the Unicode database
Surrogates are handled exceptionally

Unless an 'r' or 'R' prefix is present, escape sequences
in string and bytes literals are interpreted according to rules 
similar to those used by Standard C.

The recognized escape sequences are:

Escape Sequence  Meaning                         Notes
newline         Backslash and newline ignored
\               Backslash ()
'               Single quote (')
"               Double quote (")
a               ASCII Bell (BEL)                x07
b               ASCII Backspace (BS)            x08
f               ASCII Formfeed (FF)             x0c
n               ASCII Linefeed (LF)             x0a
r               ASCII Carriage Return (CR)      x0d
t               ASCII Horizontal Tab (TAB)      x09
v               ASCII Vertical Tab (VT)         x0b
ooo             Character with octal value ooo  (1,3)
xhh             Character with hex value hh     (2,3)

Escape sequences only recognized in string literals are:

Escape Sequence  Meaning                                      Notes

N{name}         Character named name in the Unicode database (4)
uxxxx           Character with 16-bit hex value xxxx         (5)
Uxxxxxxxx       Character with 32-bit hex value xxxxxxxx     (6)

Notes:

1. As in Standard C, up to three octal digits are accepted.
2. Unlike in Standard C, exactly two hex digits are required.
3. In a bytes literal, hexadecimal and octal escapes denote
   the byte with the given value.
   In a string literal, these escapes denote a Unicode character
   with the given value.
4. Changed in version 3.3: Support for name aliases 1 has been added.
5. Exactly four hex digits are required.
6. Any Unicode character can be encoded this way.
   Exactly eight hex digits are required.

Unlike Standard C, all unrecognized escape sequences are left 
in the string unchanged, i.e., the backslash is left in the result.

Not sure about your open() syntax. Maybe change it to the followig?

db = open( r"C:UsersDeePakOneDriveDesktopNamedatabase.txt", 'w')
Answered By: JosefZ