Class 12 Programs
- 1.Read text file line by line with # separator
- 2.Count vowels, consonants, uppercase, lowercase in file
- 3.Remove lines containing character 'a'
- 4.Binary file with name and roll number search
- 5.Binary file update marks by roll number
- 6.Random number generator (Dice Simulator)
- 7.Stack implementation using list
- 8.CSV file with user-id and password
- 9.User Defined Functions to manipulate List Store Indices of Non Zero elements &Double the Odd values
- 10.WORKING WITH BINARY FILE IN PYTHON Create a binary file, Search and display the records from the binary file
- 11.TEXT FILES IN PYTHON Remove duplicate lines from the file & Display unique words present in the file
- 12.TEXT FILES IN PYTHON Copying lines to a new file & Replacing the '-' sign with a blankspace
- 13.TEXT FILES IN PYTHON Count the lines starts with I/T & Display the lines with exactly 6 words
- 14.TEXT FILES IN PYTHON Count the occurrences of word & Count number of vowels and consonants
- 15.User Defined Functions to Manipulate List Find the Longest Word and Shifting the elements to left
- 16.IMPLEMENTATION OF STACK USING LIST IN PYTHON
- 17.ALTER table to add new attributes / modify data type / drop attribute
- 18.UPDATE table to modify data
- 19.ORDER By to display data in ascending / descending order
- 20.DELETE to remove tuple(s)
- 21.GROUP BY and find the min, max, sum, count and average
- 22.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - DELETE RECORDS
- 23.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - UPDATE RECORDS
- 24.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - INSERT RECORDS
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
- Start
- Import csv module
- Create functions for different operations (add, search, display)
- Create CSV file with headers if it doesn't exist
- Implement add_user() function to add new user records
- Implement search_user() function to find specific users
- Implement display_users() function to show all records
- Create a menu-driven interface
- Handle file operations with proper error handling
- 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
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.
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.
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.
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.
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.