Kkkk

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

1.Read a text file line by line and display each word separated by a #.

# Open the file in read mode

with open('sample.txt', 'r') as file:

# Iterate through each line in the file

for line in file:

# Remove any leading/trailing whitespace and split the line into words

words = line.strip().split()

# Join the words with a '#' and print

print('#'.join(words))

output:-

Hello#world

This#is#a#test

Python#is#awesome

2. Read a text file and display the number of vowels, consonants, uppercase, and lowercase
characters:

def count_characters_in_file(file_name):

vowels = 'aeiouAEIOU'

consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'

vowels_count = consonants_count = upper_count = lower_count = 0

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

for line in file:

for char in line:


if char in vowels:

vowels_count += 1

elif char in consonants:

consonants_count += 1

elif char.isupper():

upper_count += 1

elif char.islower():

lower_count += 1

print(f'Vowels: {vowels_count}')

print(f'Consonants: {consonants_count}')

print(f'Uppercase letters: {upper_count}')

print(f'Lowercase letters: {lower_count}')

# Usage example

count_characters_in_file('sample.txt')

output:-

Hello World

This is Python

3.Remove all the lines that contain the character 'a' in a file and write it to another file.

def remove_lines_with_a(input_file, output_file):


with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:

for line in infile:

if 'a' not in line:

outfile.write(line)

# Usage example

remove_lines_with_a('sample.txt', 'output.txt')

output:-

This is a test

Hello world

Apples are tasty

Python is fun

4.Create a binary file with name and roll number. Search for a given roll number and display the
name.

import pickle

# Create a binary file with name and roll number

def create_binary_file():

data = [

(101, 'Alice'),

(102, 'Bob'),

(103, 'Charlie')

with open('students.dat', 'wb') as file:


pickle.dump(data, file)

# Search for a roll number in the binary file

def search_roll_number(roll_number):

with open('students.dat', 'rb') as file:

students = pickle.load(file)

for roll, name in students:

if roll == roll_number:

print(f'Roll Number: {roll}, Name: {name}')

return

print('Roll number not found.')

# Usage example

create_binary_file()

search_roll_number(102)

output:-

Roll Number: 102, Name: Bob

5.Create a binary file with roll number, name, and marks. Input a roll number and update the marks

import pickle

# Create a binary file with roll number, name, and marks

def create_marks_file():

data = [

(101, 'Alice', 85),

(102, 'Bob', 90),


(103, 'Charlie', 88)

with open('marks.dat', 'wb') as file:

pickle.dump(data, file)

# Update marks for a given roll number

def update_marks(roll_number, new_marks):

with open('marks.dat', 'rb') as file:

students = pickle.load(file)

for i, (roll, name, marks) in enumerate(students):

if roll == roll_number:

students[i] = (roll, name, new_marks)

break

else:

print('Roll number not found.')

return

with open('marks.dat', 'wb') as file:

pickle.dump(students, file)

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

# Usage example

create_marks_file()

update_marks(102, 95)

output:-
Marks updated for roll number 102.

6.Write a random number generator that generates random numbers between 1 and 6 (simulating a
dice)

import random

def roll_dice():

return random.randint(1, 6)

# Usage example

print(roll_dice()) # Simulates a dice roll

output:-

4 # (Output will vary since it's random)

7.Write a Python program to implement a stack using a list

class Stack:

def __init__(self):

self.stack = []

def push(self, item):

self.stack.append(item)

def pop(self):

if len(self.stack) > 0:

return self.stack.pop()
else:

print("Stack is empty!")

return None

def peek(self):

if len(self.stack) > 0:

return self.stack[-1]

else:

print("Stack is empty!")

return None

def is_empty(self):

return len(self.stack) == 0

def size(self):

return len(self.stack)

# Usage example

stack = Stack()

stack.push(1)

stack.push(2)

stack.push(3)

print(stack.pop()) # Output: 3

print(stack.peek()) # Output: 2

output:-
3

8.Create a CSV file by entering user-id and password, read and search the password for a given user-
id

import csv

# Create a CSV file with user-id and password

def create_csv_file():

users = [

['user1', 'password1'],

['user2', 'password2'],

['user3', 'password3']

with open('users.csv', mode='w', newline='') as file:

writer = csv.writer(file)

writer.writerows(users)

# Search for password by user-id

def search_password(user_id):

with open('users.csv', mode='r') as file:

reader = csv.reader(file)

for row in reader:

if row[0] == user_id:

print(f'User ID: {row[0]}, Password: {row[1]}')

return

print('User ID not found.')


# Usage example

create_csv_file()

search_password('user2')

output:-

User ID: user2, Password: password2

You might also like