HomeComputer SciencePracticalClass 12CSV User Password

Class 12 Programs

Quick Tips

  • • Import random module for number generation
  • • Use randint(1, 6) for dice simulation
  • • Handle user input validation properly

CSV File with User-ID and Password

AIM

To write a Python program to create and manage a CSV file containing user-id and password information with operations like adding, searching, and displaying records.

ALGORITHM

  1. Start
  2. Import csv module
  3. Create functions for different operations (add, search, display)
  4. Create CSV file with headers if it doesn't exist
  5. Implement add_user() function to add new user records
  6. Implement search_user() function to find specific users
  7. Implement display_users() function to show all records
  8. Create a menu-driven interface
  9. Handle file operations with proper error handling
  10. Stop

PROGRAM

# Python program for CSV file operations with user-id and password

import csv
import os

def create_csv_file():
    """Create CSV file with headers if it doesn't exist"""
    filename = 'users.csv'
    if not os.path.exists(filename):
        with open(filename, 'w', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(['UserID', 'Password', 'Name', 'Email'])
        print(f"CSV file '{filename}' created successfully!")
    return filename

def add_user(filename):
    """Add a new user to the CSV file"""
    try:
        print("\n--- Add New User ---")
        user_id = input("Enter User ID: ")
        password = input("Enter Password: ")
        name = input("Enter Name: ")
        email = input("Enter Email: ")
        
        with open(filename, 'a', newline='') as file:
            writer = csv.writer(file)
            writer.writerow([user_id, password, name, email])
        
        print(f"User '{user_id}' added successfully!")
        
    except Exception as e:
        print(f"Error adding user: {e}")

def search_user(filename):
    """Search for a user by User ID"""
    try:
        search_id = input("\nEnter User ID to search: ")
        found = False
        
        with open(filename, 'r') as file:
            reader = csv.reader(file)
            headers = next(reader)  # Skip header row
            
            print(f"\n--- Search Results ---")
            for row in reader:
                if row[0] == search_id:
                    print(f"User ID: {row[0]}")
                    print(f"Password: {row[1]}")
                    print(f"Name: {row[2]}")
                    print(f"Email: {row[3]}")
                    found = True
                    break
        
        if not found:
            print(f"User with ID '{search_id}' not found!")
            
    except FileNotFoundError:
        print("CSV file not found!")
    except Exception as e:
        print(f"Error searching user: {e}")

def display_all_users(filename):
    """Display all users from the CSV file"""
    try:
        with open(filename, 'r') as file:
            reader = csv.reader(file)
            headers = next(reader)
            
            print(f"\n--- All Users ---")
            print(f"{'UserID':<10} {'Password':<12} {'Name':<15} {'Email':<20}")
            print("-" * 60)
            
            for row in reader:
                print(f"{row[0]:<10} {row[1]:<12} {row[2]:<15} {row[3]:<20}")
                
    except FileNotFoundError:
        print("CSV file not found!")
    except Exception as e:
        print(f"Error displaying users: {e}")

def validate_login(filename):
    """Validate user login credentials"""
    try:
        login_id = input("\nEnter User ID: ")
        login_password = input("Enter Password: ")
        
        with open(filename, 'r') as file:
            reader = csv.reader(file)
            headers = next(reader)  # Skip header row
            
            for row in reader:
                if row[0] == login_id and row[1] == login_password:
                    print(f"\nLogin successful! Welcome, {row[2]}!")
                    return True
            
            print("Invalid User ID or Password!")
            return False
            
    except FileNotFoundError:
        print("CSV file not found!")
        return False
    except Exception as e:
        print(f"Error during login: {e}")
        return False

def create_sample_data(filename):
    """Create sample user data"""
    sample_users = [
        ['admin', 'admin123', 'Administrator', 'admin@example.com'],
        ['john_doe', 'password123', 'John Doe', 'john@example.com'],
        ['jane_smith', 'secure456', 'Jane Smith', 'jane@example.com'],
        ['bob_wilson', 'mypass789', 'Bob Wilson', 'bob@example.com']
    ]
    
    with open(filename, 'a', newline='') as file:
        writer = csv.writer(file)
        for user in sample_users:
            writer.writerow(user)
    
    print("Sample user data added!")

# Main program
def main():
    print("CSV USER MANAGEMENT SYSTEM")
    print("=" * 30)
    
    # Create CSV file
    filename = create_csv_file()
    
    # Add sample data
    create_sample_data(filename)
    
    while True:
        print("\n--- Menu ---")
        print("1. Add New User")
        print("2. Search User")
        print("3. Display All Users")
        print("4. Validate Login")
        print("5. Exit")
        
        choice = input("\nEnter your choice (1-5): ")
        
        if choice == '1':
            add_user(filename)
        elif choice == '2':
            search_user(filename)
        elif choice == '3':
            display_all_users(filename)
        elif choice == '4':
            validate_login(filename)
        elif choice == '5':
            print("Thank you for using CSV User Management System!")
            break
        else:
            print("Invalid choice! Please try again.")

if __name__ == "__main__":
    main()

OUTPUT

CSV USER MANAGEMENT SYSTEM

==============================

CSV file 'users.csv' created successfully!

Sample user data added!

--- Menu ---

1. Add New User

2. Search User

3. Display All Users

4. Validate Login

5. Exit

Enter your choice (1-5): 3

--- All Users ---

UserID Password Name Email

------------------------------------------------------------

admin admin123 Administrator admin@example.com

john_doe password123 John Doe john@example.com

jane_smith secure456 Jane Smith jane@example.com

bob_wilson mypass789 Bob Wilson bob@example.com

CONCLUSION

The program successfully demonstrates CSV file operations in Python for user management. It provides functionality to create, read, search, and manage user records with proper error handling. The program uses the csv module for efficient file operations and implements a menu-driven interface for user interaction.

VIVA QUESTIONS

  1. What is CSV format and why is it used?

    CSV (Comma Separated Values) is a simple file format used to store tabular data. It's widely supported and easy to read/write.

  2. What is the purpose of newline='' parameter in open()?

    The newline='' parameter prevents extra blank lines from being inserted between rows in CSV files on Windows systems.

  3. How does csv.writer() differ from regular file writing?

    csv.writer() handles CSV formatting automatically, including proper comma placement and quote handling for special characters.

  4. What does next(reader) do in CSV reading?

    next(reader) reads and skips the first row (usually headers) so that subsequent iterations only process data rows.

  5. How can you handle CSV files with different delimiters?

    Use the delimiter parameter in csv.reader() or csv.writer(), e.g., csv.reader(file, delimiter=';') for semicolon-separated values.