Class 12 – Practical – Python Programming
Read a text file line by line and display each word separated by a #.
# Open the text file for reading
file_path = "your_file.txt" # Replace with the path to your text file
try:
with open(file_path, 'r') as file:
# Read the file line by line
for line in file:
# Split each line into words
words = line.split()
# Join the words with '#' as separator and display
word_string = "#".join(words)
print(word_string)
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Make sure to replace "your_file.txt"
with the actual path to the text file you want to read. This code will read the file line by line, split each line into words, join the words with ‘#’ as a separator, and print the resulting string for each line.
Read a text file and display the number of vowels/ consonants/ uppercase/ lowercase characters in the file.
# Define a function to check if a character is a vowel
def is_vowel(char):
vowels = "AEIOUaeiou"
return char in vowels
# Initialize counters
vowel_count = 0
consonant_count = 0
uppercase_count = 0
lowercase_count = 0
# Open the text file for reading
file_path = "your_file.txt" # Replace with the path to your text file
try:
with open(file_path, 'r') as file:
# Read the entire file content
content = file.read()
# Iterate through each character in the content
for char in content:
if char.isalpha():
if is_vowel(char):
vowel_count += 1
else:
consonant_count += 1
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
# Display the counts
print("Vowels:", vowel_count)
print("Consonants:", consonant_count)
print("Uppercase:", uppercase_count)
print("Lowercase:", lowercase_count)
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Replace "your_file.txt"
with the actual path to your text file. This code will open the file, read its content, and count the number of vowels, consonants, uppercase, and lowercase characters in the file.
Remove all the lines that contain the character ‘a’ in a file and write it to another file.
# Define the input and output file paths
input_file_path = "input_file.txt" # Replace with your input file path
output_file_path = "output_file.txt" # Replace with your output file path
try:
with open(input_file_path, 'r') as input_file, open(output_file_path, 'w') as output_file:
# Read each line from the input file
for line in input_file:
# Check if the line contains the character 'a' (case-insensitive)
if 'a' not in line.lower():
# If 'a' is not present, write the line to the output file
output_file.write(line)
print("Lines containing 'a' removed and written to", output_file_path)
except FileNotFoundError:
print(f"Input file '{input_file_path}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Make sure to replace "input_file.txt"
with the actual path to your input file and "output_file.txt"
with the desired path for the output file. This code reads each line from the input file and checks if it contains the character ‘a’ (case-insensitive). If ‘a’ is not present in the line, it writes the line to the output 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.
import struct
# Function to write data to the binary file
def write_to_binary_file(file_name, data):
with open(file_name, 'wb') as file:
for entry in data:
name, roll_number = entry
# Pack the data into a binary format (assuming both name and roll number are strings)
packed_data = struct.pack('20sI', name.encode('utf-8'), roll_number)
file.write(packed_data)
# Function to search for a roll number in the binary file
def search_roll_number(file_name, roll_number):
with open(file_name, 'rb') as file:
while True:
packed_data = file.read(struct.calcsize('20sI'))
if not packed_data:
break
name, stored_roll_number = struct.unpack('20sI', packed_data)
name = name.decode('utf-8').strip('\x00') # Decode and remove null bytes
if roll_number == stored_roll_number:
return name
return None
# Create a binary file with name and roll number data
data = [("John", 101), ("Alice", 102), ("Bob", 103)]
file_name = "student_data.bin"
write_to_binary_file(file_name, data)
# Search for a roll number and display the name
search_roll = 102 # Replace with the roll number you want to search for
result = search_roll_number(file_name, search_roll)
if result:
print(f"Name for Roll Number {search_roll}: {result}")
else:
print(f"Roll Number {search_roll} not found.")
This code defines two functions: write_to_binary_file
to create a binary file with name and roll number data, and search_roll_number
to search for a roll number in the binary file and return the corresponding name. Replace the data
list with your own name and roll number data. Finally, specify the roll number you want to search for in the search_roll
variable.
Create a binary file with roll number, name and marks. Input a roll number and update the marks.
import struct
# Function to write data to the binary file
def write_to_binary_file(file_name, data):
with open(file_name, 'wb') as file:
for entry in data:
roll_number, name, marks = entry
# Pack the data into a binary format
packed_data = struct.pack('I20sH', roll_number, name.encode('utf-8'), marks)
file.write(packed_data)
# Function to update marks for a given roll number
def update_marks(file_name, roll_number, new_marks):
data = []
with open(file_name, 'rb') as file:
while True:
packed_data = file.read(struct.calcsize('I20sH'))
if not packed_data:
break
stored_roll_number, name, marks = struct.unpack('I20sH', packed_data)
name = name.decode('utf-8').strip('\x00') # Decode and remove null bytes
if roll_number == stored_roll_number:
# Update marks for the specified roll number
data.append((roll_number, name, new_marks))
else:
data.append((stored_roll_number, name, marks))
# Write the updated data back to the file
write_to_binary_file(file_name, data)
# Create a binary file with roll number, name, and marks data
data = [(101, "John", 85), (102, "Alice", 92), (103, "Bob", 78)]
file_name = "student_data.bin"
write_to_binary_file(file_name, data)
# Input a roll number and update the marks
update_roll = 102 # Replace with the roll number you want to update
new_marks = 95 # Replace with the new marks
update_marks(file_name, update_roll, new_marks)
print(f"Marks for Roll Number {update_roll} updated to {new_marks}.")
This code defines two functions: write_to_binary_file
to create a binary file with roll number, name, and marks data, and update_marks
to update the marks for a given roll number. Replace the data
list with your own roll number, name, and marks data. Finally, specify the roll number you want to update (update_roll
) and the new marks (new_marks
).
Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
import random
def roll_dice():
return random.randint(1, 6)
# Simulate rolling the dice 5 times
for _ in range(5):
result = roll_dice()
print("You rolled:", result)
In this code:
- We import the
random
module. - We define a function
roll_dice
that usesrandom.randint(1, 6)
to generate a random integer between 1 and 6, inclusive. - We simulate rolling the dice 5 times in the
for
loop and print the result.
You can change the number of times you want to simulate rolling the dice by modifying the value in the range()
function.
Write a Python program to implement a stack using list.
You can implement a stack using a Python list quite easily. In a stack, elements are added and removed in a Last-In-First-Out (LIFO) order. Here’s a basic Python program that demonstrates how to create a stack using a list:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
return None # Stack is empty
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
return None # Stack is empty
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# Create a stack
stack = Stack()
# Push elements onto the stack
stack.push(1)
stack.push(2)
stack.push(3)
# Pop elements from the stack
print("Popped:", stack.pop()) # Removes and prints 3
print("Popped:", stack.pop()) # Removes and prints 2
# Check the top element without popping it
print("Peek:", stack.peek()) # Peeks at 1
# Check if the stack is empty
print("Is empty:", stack.is_empty()) # False
# Get the size of the stack
print("Size:", stack.size()) # 1
In this code:
- We create a
Stack
class that uses a list (self.items
) to store elements. - The
push
method adds an element to the top of the stack. - The
pop
method removes and returns the top element from the stack. - The
peek
method returns the top element without removing it. - The
is_empty
method checks if the stack is empty. - The
size
method returns the number of elements in the stack.
You can create a stack object and perform stack operations as shown in the code.
Create a CSV file by entering user-id and password, read and search the password for given userid.
You can create a CSV file to store user IDs and passwords, and then read and search for a password for a given user ID using Python. Here’s a basic example of how to do this:
1. Creating a CSV File:First, create a CSV file to store user ID and password pairs. You can do this manually or programmatically. For this example, we’ll create it programmatically:
import csv
# Data to be written to the CSV file (user-id, password)
data = [("user1", "password1"),
("user2", "password2"),
("user3", "password3")]
# Write data to the CSV file
with open("user_credentials.csv", mode="w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
2. Reading and Searching for Password:
Next, you can read the CSV file and search for a password based on a given user ID:
import csv
# Function to search for a password based on user ID
def search_password(user_id):
with open("user_credentials.csv", mode="r") as file:
reader = csv.reader(file)
for row in reader:
if row[0] == user_id:
return row[1]
return None # User ID not found
# Input the user ID to search for
user_id_to_search = input("Enter User ID: ")
# Search for the password and display the result
password = search_password(user_id_to_search)
if password:
print(f"Password for {user_id_to_search}: {password}")
else:
print(f"User ID {user_id_to_search} not found.")
In this code:
- We define a
search_password
function that reads the CSV file and searches for the password corresponding to the provided user ID. - We input the user ID to search for and then call the
search_password
function to find and display the password or a message if the user ID is not found.
Note: Remember to replace the data in the CSV file with your own user IDs and passwords. Additionally, this example is for educational purposes and doesn’t consider security best practices for storing passwords; in a real-world application, you should use proper password hashing and storage techniques.