Simple Python Login System with TXT Files

Published on: May 29, 2026
Reading time: 5 minutes
Sistema de login simples desenvolvido com Python

Learning to handle external data is one of the major milestones in any programmer’s journey. If you are taking your first steps in Python programming logic, understanding how to save and validate user data is essential. Building a simple login system with Python and TXT files is the perfect project to practice file reading and writing concepts, as well as flow control structures in a practical and direct way.

Although professional applications use robust databases like MySQL or PostgreSQL, using plain text files offers a lightweight and educational way to understand data persistence. In this guide, you will build from scratch a system capable of registering new users and validating access for existing profiles, saving everything in a regular file on your computer.

Why use TXT files for a login system?

Text files are ideal for small scripts, local automation tools, or quick prototypes. The main advantage is simplicity: you do not need to install complex database servers or configure network connections. Everything you need is Python’s built-in file system functions.

Working with TXT also reinforces knowledge of how Python strings are manipulated and how the computer interprets line breaks and separators. It is a solid foundation before advancing to more structured formats like JSON or relational databases.

Setting up the development environment

Make sure Python is installed on your machine before writing any code. For a better writing and debugging experience, we recommend installing and configuring VS Code, which has excellent Python extensions.

Create a dedicated folder for this project. Inside it, you will work with two main files: a Python script (e.g. main.py) and a text file where credentials will be stored (e.g. users.txt). You do not need to create the TXT file manually; the code can do it automatically if it does not exist.

Basic structure of the login system

The system will be divided into three main functions: an interactive menu, a function to register new users, and a function to perform the login. To organize the flow, the concept of Python functions is used, which makes the code cleaner and easier to maintain.

Step 1: Creating the options menu

def menu():
    print("n--- ACCESS SYSTEM ---")
    print("1. Register new user")
    print("2. Login")
    print("3. Exit")
    option = input("Choose an option: ")
    return option

The input() function captures the user’s choice. This is a simple form of interaction that serves as the foundation for many terminal scripts.

Step 2: Building the registration function

Each user’s username and password will be saved on a new line, separated by a comma. This keeps the file organized and easy to read back line by line.

def register():
    username = input("Enter new username: ")
    password = input("Enter new password: ")

    with open("users.txt", "a") as file:
        file.write(f"{username},{password}n")
    print("User registered successfully!")

The with open() context manager is the recommended way to open files in Python, as it guarantees the file is properly closed even if an error occurs during writing. The "a" (append) mode adds content to the end of the file without erasing existing data.

Step 3: Login validation logic

The validation reads users.txt, iterates through each line, and checks whether the entered username/password pair matches any saved record.

def login():
    username_input = input("Username: ")
    password_input = input("Password: ")
    success = False

    try:
        with open("users.txt", "r") as file:
            for line in file:
                saved_user, saved_pass = line.strip().split(",")
                if username_input == saved_user and password_input == saved_pass:
                    success = True
                    break
    except FileNotFoundError:
        print("Error: No users registered yet.")
        return

    if success:
        print("Login successful! Welcome.")
    else:
        print("Incorrect username or password.")

The strip() method removes whitespace and line breaks, and split(",") separates the username from the password. A try-except block prevents the program from crashing if the text file does not yet exist.

Improving security with password hashing

Storing passwords in plain text, as done above, is insecure. Anyone with access to the TXT file can read all passwords. In real projects, cryptographic techniques known as “hashing” are applied. Python offers native libraries like hashlib to transform a password into an unrecognizable string of characters. Although this tutorial focuses on the basics, it is highly recommended to study password hashing in Python to evolve the security of your systems.

Handling common errors

One of the most common issues is a user attempting to log in before any registrations exist, which triggers the file-not-found error. Another frequent problem is inserting commas in the username field, which breaks the split(",") logic. For a more robust system, add validations to block special characters or ensure fields are not left empty. If, elif, and else structures help create those protection layers.

Organizing the main flow

def run():
    while True:
        choice = menu()
        if choice == "1":
            register()
        elif choice == "2":
            login()
        elif choice == "3":
            print("Exiting the system...")
            break
        else:
            print("Invalid option!")

Complete project script

Copy the block below, save it as login_system.py, and run it immediately in your terminal.

# Simple Python Login System with TXT Files

def menu():
    """Displays the main menu and returns the chosen option."""
    print("n" + "=" * 20)
    print("   ACCESS SYSTEM")
    print("=" * 20)
    print("1. Register new user")
    print("2. Login")
    print("3. Exit")
    return input("Choose an option: ")

def register():
    """Registers a new user in the users.txt file."""
    username = input("Enter new username: ").strip()
    password = input("Enter new password: ").strip()

    if not username or not password:
        print("Error: Username and password cannot be empty.")
        return

    # Mode 'a' appends to the file without overwriting
    with open("users.txt", "a") as file:
        file.write(f"{username},{password}n")

    print(f"User '{username}' registered successfully!")

def login():
    """Validates credentials against the users.txt file."""
    username_input = input("Username: ").strip()
    password_input = input("Password: ").strip()

    found = False

    try:
        with open("users.txt", "r") as file:
            for line in file:
                # Split the line by comma and remove whitespace/line breaks
                parts = line.strip().split(",")
                if len(parts) == 2:
                    saved_user, saved_pass = parts
                    if username_input == saved_user and password_input == saved_pass:
                        found = True
                        break
    except FileNotFoundError:
        print("Warning: No user database found. Please register a user first.")
        return

    if found:
        print(f"Success: Welcome to the system, {username_input}!")
    else:
        print("Error: Incorrect username or password.")

def start():
    """Controls the main program flow."""
    while True:
        option = menu()

        if option == "1":
            register()
        elif option == "2":
            login()
        elif option == "3":
            print("Shutting down. See you!")
            break
        else:
            print("Invalid option. Please try again.")

if __name__ == "__main__":
    start()

Tips to expand the project

Once you have mastered this basic system, you can start adding more advanced features. An excellent idea is to create a Python password generator integrated into the registration function, to suggest strong combinations to the user.

Another natural evolution is building a visual interface. Instead of reading and writing only in the terminal, you can use libraries like Tkinter to create graphical interfaces with Python, making the login system much more professional for everyday users. For further reading, the official Python pathlib documentation covers modern file system management in detail.

Frequently Asked Questions

Is a TXT file safe for storing passwords?

No. TXT files can be read by anyone with computer access. For real projects, use databases and password hashing.

What happens if I delete the users.txt file?

All registrations will be lost. When attempting to log in, Python will display the error message handled in the try-except block.

How can I allow commas in the password?

In this simple system, commas break the split command. To fix it, use a rarer separator (like | or ;) or migrate to JSON files.

Can I use this system on a web page?

For the web, frameworks like Flask or Django are ideal — they have built-in authentication systems that are far more secure.

How do I hide the password while typing in the terminal?

Import the native getpass module and use getpass.getpass() instead of input() for the password field.

Does Python create the file automatically?

Yes. The "a" (append) mode of the open() command creates the file automatically if it does not exist in the current directory.

Can two users share the same username?

In this simplified version, yes. To prevent it, add logic that checks whether the username already exists in the TXT before saving the new registration.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Python PDF search with RAG
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Python PDF Search with RAG

    Build Python PDF search with RAG, semantic retrieval, grounded answers, evaluation, and document security.

    Ler mais

    Tempo de leitura: 6 minutos
    23/07/2026
    Criação de chatbot com API da OpenAI usando Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Python Chatbot with the OpenAI API

    Build a Python chatbot with the OpenAI Responses API, secure environment variables, conversation memory, model configuration, and practical error handling.

    Ler mais

    Tempo de leitura: 7 minutos
    10/07/2026
    Chatbot simples em Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Simple Chatbot with Python

    Build a simple Python chatbot with rules, input normalization, intents, random replies, JSON data, conversation loops, tests, and practical extension

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Criptografia e segurança de dados em Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Secure Password Generator in Python

    Build a secure password generator in Python with secrets, configurable character rules, a CLI, passphrases, validation, and practical tests.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Jogo da forca para iniciantes desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Hangman Game in Python

    Build a complete Hangman game in Python with random words, input validation, repeated-letter checks, lives, ASCII art, and replay support.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Quiz interativo no terminal desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Terminal Quiz Game in Python

    Build a terminal quiz game in Python with questions, input validation, scoring, shuffled answers, replay support, JSON loading, and tests.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026