0% found this document useful (0 votes)
5 views13 pages

Cs Practical

The document contains multiple Python code examples demonstrating file operations, including reading and processing text files, counting characters, removing lines, creating and searching binary files, simulating dice rolls, implementing a stack, and managing user data in CSV format. Each section includes code snippets, example usage, and sample outputs to illustrate functionality. The examples cover a range of programming concepts suitable for beginners to intermediate learners.

Uploaded by

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

Cs Practical

The document contains multiple Python code examples demonstrating file operations, including reading and processing text files, counting characters, removing lines, creating and searching binary files, simulating dice rolls, implementing a stack, and managing user data in CSV format. Each section includes code snippets, example usage, and sample outputs to illustrate functionality. The examples cover a range of programming concepts suitable for beginners to intermediate learners.

Uploaded by

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

1.

Read a Text File Line by Line and Display Each Word Separated by a #

Code:

def display_words_with_hash(filename):

try:

with open(filename, 'r') as file:

for line in file:

words = line.strip().split()

print('#'.join(words))

except FileNotFoundError:

print(f"The file {filename} does not exist.")

# Example usage

if __name__ == "__main__":

filename = 'input.txt' # Replace with your file name

display_words_with_hash(filename)

Sample input.txt:

Hello World

Python Programming is fun

OpenAI ChatGPT

Output:

Hello#World

Python#Programming#is#fun

OpenAI#ChatGPT

2.Read a Text File and Display the Number of


Vowels/Consonants/Uppercase/Lowercase Characters
Code:

def count_characters(filename):

vowels = set('aeiouAEIOU')

vowel_count = consonant_count = uppercase_count = lowercase_count = 0

try:

with open(filename, 'r') as file:

for line in file:

for char in line:

if char.isalpha():

if char in vowels:

vowel_count += 1

else:

consonant_count += 1

if char.isupper():

uppercase_count += 1

elif char.islower():

lowercase_count += 1

print(f"Vowels: {vowel_count}")

print(f"Consonants: {consonant_count}")

print(f"Uppercase Characters: {uppercase_count}")

print(f"Lowercase Characters: {lowercase_count}")

except FileNotFoundError:

print(f"The file {filename} does not exist.")


# Example usage

if __name__ == "__main__":

filename = 'input.txt' # Replace with your file name

count_characters(filename)

Sample Output:

Vowels: 10

Consonants: 20

Uppercase Characters: 5

Lowercase Characters: 25

3. Remove All Lines That Contain the Character 'a' in a File and Write to Another File

Code:

def remove_lines_with_a(input_filename, output_filename):

try:

with open(input_filename, 'r') as infile, open(output_filename, 'w') as outfile:

for line in infile:

if 'a' not in line.lower():

outfile.write(line)

print(f"Lines without 'a' have been written to {output_filename}.")

except FileNotFoundError:

print(f"The file {input_filename} does not exist.")

# Example usage

if __name__ == "__main__":

input_filename = 'input.txt' # Replace with your input file name

output_filename = 'output.txt' # Replace with your desired output file name


remove_lines_with_a(input_filename, output_filename)

Sample input.txt:

Apple is red

Banana is yellow

Grapes are tasty

Cherry is sweet

Sample output.txt:

Cherry is sweet

4. Create a Binary File with Name and Roll Number. Search for a Given Roll Number
and Display the Name

Code:

import pickle

def create_binary_file(filename, records):

with open(filename, 'wb') as file:

pickle.dump(records, file)

print(f"Data has been written to {filename}.")

def search_roll_number(filename, roll_number):

try:

with open(filename, 'rb') as file:

records = pickle.load(file)

for record in records:

if record['roll_number'] == roll_number:

print(f"Name: {record['name']}")
return

print("Roll number not found.")

except FileNotFoundError:

print(f"The file {filename} does not exist.")

# Example usage

if __name__ == "__main__":

filename = 'students.bin'

records = [

{'roll_number': 101, 'name': 'Alice'},

{'roll_number': 102, 'name': 'Bob'},

{'roll_number': 103, 'name': 'Charlie'},

create_binary_file(filename, records)

# Search for a roll number

roll_number_to_search = 102 # Change as needed

search_roll_number(filename, roll_number_to_search)

Sample Output:

Data has been written to students.bin.

Name: Bob

5. Create a Binary File with Roll Number, Name, and Marks. Update Marks for a Given
Roll Number

Code:

import pickle
def create_binary_file(filename, records):

with open(filename, 'wb') as file:

pickle.dump(records, file)

print(f"Data has been written to {filename}.")

def update_marks(filename, roll_number, new_marks):

try:

with open(filename, 'rb') as file:

records = pickle.load(file)

for record in records:

if record['roll_number'] == roll_number:

record['marks'] = new_marks

print(f"Marks updated for roll number {roll_number}.")

break

else:

print("Roll number not found.")

return

with open(filename, 'wb') as file:

pickle.dump(records, file)

except FileNotFoundError:

print(f"The file {filename} does not exist.")


def display_records(filename):

try:

with open(filename, 'rb') as file:

records = pickle.load(file)

for record in records:

print(record)

except FileNotFoundError:

print(f"The file {filename} does not exist.")

# Example usage

if __name__ == "__main__":

filename = 'students_marks.bin'

records = [

{'roll_number': 101, 'name': 'Alice', 'marks': 85},

{'roll_number': 102, 'name': 'Bob', 'marks': 90},

{'roll_number': 103, 'name': 'Charlie', 'marks': 75},

create_binary_file(filename, records)

print("\nBefore update:")

display_records(filename)

# Update marks

roll_number_to_update = 102 # Change as needed

new_marks = 95
update_marks(filename, roll_number_to_update, new_marks)

print("\nAfter update:")

display_records(filename)

Sample Output:

Data has been written to students_marks.bin.

Before update:

{'roll_number': 101, 'name': 'Alice', 'marks': 85}

{'roll_number': 102, 'name': 'Bob', 'marks': 90}

{'roll_number': 103, 'name': 'Charlie', 'marks': 75}

Marks updated for roll number 102.

After update:

{'roll_number': 101, 'name': 'Alice', 'marks': 85}

{'roll_number': 102, 'name': 'Bob', 'marks': 95}

{'roll_number': 103, 'name': 'Charlie', 'marks': 75}

6. Write a Random Number Generator That Generates Random Numbers Between 1


and 6 (Simulates a Dice)

Code:

import random

def roll_dice():

return random.randint(1, 6)
# Example usage

if __name__ == "__main__":

number_of_rolls = 10 # Change as needed

print("Dice Rolls:")

for _ in range(number_of_rolls):

print(roll_dice(), end=' ')

print()

Sample Output:

Dice Rolls:

3526142635

7. Implement a Stack Using a List

Code:

class Stack:

def __init__(self):

self.stack = []

def push(self, item):

self.stack.append(item)

print(f"Pushed: {item}")

def pop(self):

if not self.is_empty():

item = self.stack.pop()

print(f"Popped: {item}")

return item
else:

print("Stack is empty.")

def peek(self):

if not self.is_empty():

print(f"Top item: {self.stack[-1]}")

return self.stack[-1]

else:

print("Stack is empty.")

def is_empty(self):

return len(self.stack) == 0

def display(self):

print("Stack:", self.stack)

# Example usage

if __name__ == "__main__":

stack = Stack()

stack.push(10)

stack.push(20)

stack.push(30)

stack.display()

stack.peek()

stack.pop()
stack.display()

stack.pop()

stack.pop()

stack.pop() # Attempt to pop from empty stack

Sample Output:

Pushed: 10

Pushed: 20

Pushed: 30

Stack: [10, 20, 30]

Top item: 30

Popped: 30

Stack: [10, 20]

Popped: 20

Popped: 10

Stack is empty.

8. Create a CSV File by Entering User-ID and Password, Read and Search the
Password for a Given User-ID

Code:

import csv

import os

def create_csv(filename):

with open(filename, 'w', newline='') as csvfile:

fieldnames = ['user_id', 'password']

writer = csv.DictWriter(csvfile, fieldnames=fieldnames)


writer.writeheader()

while True:

user_id = input("Enter User ID (or 'exit' to stop): ")

if user_id.lower() == 'exit':

break

password = input("Enter Password: ")

writer.writerow({'user_id': user_id, 'password': password})

print(f"User data has been written to {filename}.")

def search_password(filename, search_user_id):

if not os.path.exists(filename):

print(f"The file {filename} does not exist.")

return

with open(filename, 'r', newline='') as csvfile:

reader = csv.DictReader(csvfile)

for row in reader:

if row['user_id'] == search_user_id:

print(f"Password for user '{search_user_id}': {row['password']}")

return

print("User ID not found.")

# Example usage

if __name__ == "__main__":

filename = 'users.csv'
# Create CSV file

create_csv(filename)

# Search for a password

search_user_id = input("Enter User ID to search: ")

search_password(filename, search_user_id)

Sample Interaction:

Enter User ID (or 'exit' to stop): user1

Enter Password: pass123

Enter User ID (or 'exit' to stop): user2

Enter Password: secret

Enter User ID (or 'exit' to stop): exit

User data has been written to users.csv.

Enter User ID to search: user1

Password for user 'user1': pass123

Sample users.csv:

user_id,password

user1,pass123

user2,secret

You might also like