0% found this document useful (0 votes)
16 views1 page

Cs Practical 12

The document outlines a series of Python functions and classes for file processing, character counting, stack implementation, and CSV file handling. It also includes SQL commands for managing a student database, such as creating tables, modifying attributes, and performing data manipulations. Additionally, it describes the integration of SQL with Python for database operations.

Uploaded by

ramminz567
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views1 page

Cs Practical 12

The document outlines a series of Python functions and classes for file processing, character counting, stack implementation, and CSV file handling. It also includes SQL commands for managing a student database, such as creating tables, modifying attributes, and performing data manipulations. Additionally, it describes the integration of SQL with Python for database operations.

Uploaded by

ramminz567
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

1.def process_file(file_path): with open(file_path, 'r') as file: 3.def remove_lines_with_character(file_path, character, 4.

import pickle
try: with open(file_path, 'r') as file: content = file.read() output_file_path): def create_file(name, roll_number):
for line in file: for char in content: try: with open('students.bin', 'ab') as file:
words = line.split() if char.isalpha(): with open(file_path, 'r') as file: pickle.dump((name, roll_number), file)
formatted_line = '#'.join(words) if char.isupper(): lines = file.readlines() def search_roll_number(roll_number):
print(formatted_line) uppercase_count += 1 # Remove lines containing the specified character with open('students.bin', 'rb') as file:
except FileNotFoundError: elif char.islower(): modified_lines = [line for line in lines if character not in while True:
line]
print(f"File '{file_path}' not found.") lowercase_count += 1 try:
with open(output_file_path, 'w') as output_file:
except Exception as e: if char in vowels: name, number = pickle.load(file)
output_file.writelines(modified_lines)
print(f"An error occurred: {e}") vowel_count += 1 if number == roll_number:
print(f"Lines containing '{character}' removed. Modified
# Replace 'your_file.txt' with the actual path of your text file elif char in consonants: return name
content saved to '{output_file_path}'.")
file_path = 'yuvi.txt' consonant_count += 1 except EOFError:
except FileNotFoundError:
process_file(file_path) print(f"Uppercase characters: {uppercase_count}") break
print(f"File '{file_path}' not found.")
2.def count_characters(file_path): print(f"Lowercase characters: {lowercase_count}") return None
except Exception as e:
vowels = "aeiouAEIOU" print(f"Vowels: {vowel_count}") # Create some data
print(f"An error occurred: {e}")
consonants = print(f"Consonants: {consonant_count}") create_file('John Doe', 1)
# Replace 'input_file.txt', 'output_file.txt', and 'a' with the
"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" except FileNotFoundError: create_file('Jane Doe', 2)
actual paths and character
uppercase_count = 0 print(f"File '{file_path}' not found.") # Search for a roll number
input_file_path = 'file.txt'
lowercase_count = 0 except Exception as e: name = search_roll_number(1)
output_file_path = ‘file.txt'
vowel_count = 0 print(f"An error occurred: {e}") if name is not None:
character_to_remove = 'a'
consonant_count = 0 file_path = 'file.txt' print(f'Name: {name}')
remove_lines_with_character(input_file_path,
try: count_characters(file_path) character_to_remove, output_file_path) else: print('Roll number not found.')

5.class Stack: # Example usage if not self.is_empty(): 8.import csv


def __init__(self): stack = Stack() popped_item = self.items.pop() def create_csv():
self.items = [] stack.push(10) print(f"Popped: {popped_item}") # Open the CSV file in write mode
def is_empty(self): stack.push(20) return popped_item with open('user_passwords.csv', 'w', newline='') as file:
return len(self.items) == 0 stack.push(30) else: writer = csv.writer(file)
def push(self, item): stack.display() print("Stack is empty. Cannot pop.") writer.writerow(["user_id", "password"])
self.items.append(item) stack.pop() def display(self): # Get user-id and password from the user
print(f"Pushed: {item}") stack.pop() if not self.is_empty(): while True:
def pop(self): stack.display() print("Stack Contents:") user_id = input("Enter user-id (or 'quit' to stop): ")
if not self.is_empty(): 6.import math.random for item in reversed(self.items): if user_id.lower() == 'quit':
popped_item = self.items.pop() def generate_random_number(): print(item) break
print(f"Popped: {popped_item}") return random.randint(1, 6) else: password = input("Enter password: ")
return popped_item print(generate_random_number()) print("Stack is empty.") writer.writerow([user_id, password])
else: 7.class Stack: # Example usage def search_password(user_id):
print("Stack is empty. Cannot pop.") def __init__(self): stack = Stack() # Open the CSV file in read mode
def display(self): self.items = [] stack.push(10) with open('user_passwords.csv', 'r') as file:
if not self.is_empty(): def is_empty(self): stack.push(20) reader = csv.reader(file)
print("Stack Contents:") return len(self.items) == 0 stack.push(30) next(reader) # Skip the header row
for item in reversed(self.items): def push(self, item): stack.display() # Search for the password of the given user-id
print(item) self.items.append(item) stack.pop() for row in reader:
else: print(f"Pushed: {item}") stack.pop() if row[0] == user_id:
print("Stack is empty.") def pop(self): stack.display() return row[1]

1.-- Create a student table -- ALTER table to drop an attribute AVG(age) AS avg_age
return None # Return None if no user-id is found CREATE TABLE IF NOT EXISTS student ( ALTER TABLE student FROM student;
# Create the CSV file student_id INT PRIMARY KEY, DROP COLUMN marks; 2.import re
create_csv() first_name VARCHAR(50) NOT NULL, -- UPDATE table to modify data import mysql.connector
# Search for a password last_name VARCHAR(50) NOT NULL, UPDATE student cnx=mysql.connector.connect(user='root',host='127.0.0.1',pass
user_id = input("Enter user-id to search for: ") age INT, SET age = 21 word='',

password = search_password(user_id) marks INT); WHERE student_id = 3; database="etelaat")

if password is not None: -- Insert data into the student table -- ORDER BY to display data in ascending order of age reg = '^\w+([\.-]?\w+)*@(\w[a-z,A-Z]*)(\.)(\w[a-z,A-Z]*)'

print(f"The password for user-id {user_id} is {password}") INSERT INTO student (student_id, first_name, last_name, age, SELECT * FROM student email=input()

else: marks) ORDER BY age ASC; # username=email

print(f"No user-id {user_id} found") VALUES -- ORDER BY to display data in descending order of marks password=input()
(1, 'John', 'Doe', 18, 85), SELECT * FROM student def check(email):
(2, 'Jane', 'Smith', 19, 92), ORDER BY marks DESC; if(re.search(reg,email)):
(3, 'Alice', 'Johnson', 20, 78), -- DELETE to remove a tuple cursor=cnx.cursor()
(4, 'Bob', 'Williams', 18, 95); DELETE FROM student cursor.execute('INSERT INTO etelaatevorod
-- Display the student table VALUES(\'%s\',\'%s\')' %(email,password))
WHERE student_id = 2;
SELECT * FROM student; print("writed into db")
-- GROUP BY and find the min, max, sum, count, and average
-- ALTER table to add a new attribute cnx.commit()
SELECT
ALTER TABLE student else:
MIN(age) AS min_age,
ADD COLUMN email VARCHAR(100); print("[email protected]")
MAX(age) AS max_age,
-- ALTER table to modify data type email1=input()
SUM(age) AS total_age,
ALTER TABLE student email=email1
COUNT(*) AS total_students,
MODIFY COLUMN age VARCHAR(3); check(email) check(email) cnx.close()

● Read a text file line by line and display each word separated
by a #.
● Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the
file.
● Remove all the lines that contain the character 'a' in a file
and write it to another file.
● Create a binary file with name and roll number. Search for a
given roll number and display the name, if not found display
appropriate message.
● Create a binary file with roll number, name and marks. Input
a roll number and update the marks.
● Write a random number generator that generates random
numbers between 1 and 6 (simulates a dice).
● Write a Python program to implement a stack using list.
● Create a CSV file by entering user-id and password, read and
search the password for given userid.

● Create a student table and insert data. Implement the


following SQL commands on the student table: o ALTER table
to add new attributes / modify data type / drop attribute o
UPDATE table to modify data o ORDER By to display data in
ascending / descending order o DELETE to remove tuple(s) o
GROUP BY and find the min, max, sum, count and average
● Integrate SQL with Python by importing suitable module

You might also like