0% found this document useful (0 votes)
64 views

Python .13 18

The document describes programs to perform various operations on text files like reading and writing lines, counting lines and words, checking file pointer positions, etc. It contains code snippets to demonstrate file handling in Python by opening, reading, writing and modifying text files.

Uploaded by

makanijenshi2409
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Python .13 18

The document describes programs to perform various operations on text files like reading and writing lines, counting lines and words, checking file pointer positions, etc. It contains code snippets to demonstrate file handling in Python by opening, reading, writing and modifying text files.

Uploaded by

makanijenshi2409
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Enrollment No: 202203103510061

Practical-13
Aim: Using concept of regular expressions, write a program to check the
validity of password input by users.

Following are the criterias for checking the password:

i. At least 1 letter between [a-z]

ii. At least 1 number between [0-9]

iii. At least 1 letter between [A-Z]

iv. At least 1 special character

v. Min. length of transaction password: 6

vi. Max. length of transaction password: 12

Code:
import re
def check_password(password):
# At least 1 letter between [a-z]
if not re.search("[a-z]", password):
return False

# At least 1 number between [0-9]


if not re.search("[0-9]", password):
return False

# At least 1 letter between [A-Z]


if not re.search("[A-Z]", password):
return False

# At least 1 special character


if not re.search("[!@#$%^&*()-_+=]", password):
return False

# Min. length of transaction password: 6, Max. length of transaction password: 12


if len(password) < 6 or len(password) > 12:
return False

UTU/CGPIT/IT/SEM-4/Programming with Python 28


Enrollment No: 202203103510061

return True

# Example usage
password = input("Enter your password: ")
if check_password(password):
print("Valid password")
else:
print("Invalid password")

Output:

UTU/CGPIT/IT/SEM-4/Programming with Python 29


Enrollment No: 202203103510061

Practical-14

Aim: a. Define a class named “Institute” and its subclass “Branch”. The
Institute class has a function that
takes two values as arguments “course” and “semester” to initialize
object of both classes. Subclass
Branch has its own attributes “name” and “enrollment_no”. “Institute”
class has display() method
to print course and semester details of student. “Branch” class also has
method called display() to
print value of name and enrollment_no.

b. Write a python program to perform the following. There is class called


“grandfather” having a
member “name”. A “father” class inherits the properties of “grandfather”
and have its own member
“city”. Now, there is a “child” class that inherits “father” class and have
“age” member. All three
classes have methods to initialize their own members and show()
methods todisplay respective
information. Create a “child” class object to initialize all members and
print details.

a) Define a class named “Institute” and its subclass “Branch”. The


Institute class has a function that takes two values as arguments
“course” and “semester” to initialize object of both classes. Subclass
Branch has its own attributes “name” and “enrollment_no”. “Institute”
class has display() method to print course and semester details of
student. “Branch” class also has method called display() to print value
of name and enrollment_no.

UTU/CGPIT/IT/SEM-4/Programming with Python 30


Enrollment No: 202203103510061

Code:
class Institute:
def __init__(self, course, semester):
self.course = course
self.semester = semester

def display(self):
print("Course:", self.course)
print("Semester:", self.semester)

class Branch(Institute):
def __init__(self, course, semester, name, enrollment_no):
super().__init__(course, semester)
self.name = name
self.enrollment_no = enrollment_no

def display(self):
super().display()
print("Name:", self.name)
print("Enrollment No:", self.enrollment_no)

# Example usage:
student = Branch("Computer Science", "3rd", "Makani Jenshi", "202203103510061")
student.display()

Output:

b) Write a python program to perform the following. There is class


called “grandfather” having a member “name”. A “father” class
inherits the properties of “grandfather” and have its own member
“city”. Now, there is a “child” class that inherits “father” class and have
“age” member. All three classes have methods to initialize their own
members and show() methods todisplay respective information.
Create a “child” class object to initialize all members and print details.

UTU/CGPIT/IT/SEM-4/Programming with Python 31


Enrollment No: 202203103510061

Code:
class Grand_father:
def __init__(self, name):
self.name = name

# def show(self):
# print("Name", self.name)

class Father(Grand_father):
def __init__(self,name,city):
super().__init__(name)
self.city =city

class Child(Father):
def __init__(self,name,city,age):
super().__init__(name,city)
self.age= age

def show(self):
#super().show()
print("Name:", self.name)
print("City:", self.city)
print("Age:", self.age)

# Example usage:
Child = Child("Jenshi", "Surat", 19)
Child.show()

Output:

UTU/CGPIT/IT/SEM-4/Programming with Python 32


Enrollment No: 202203103510061

Practical-15
Aim: Write a python program that

a. Demonstrates various modes used with file.

b. Reads data from text file in reverse order and write it into another file.

a) Demonstrates various modes used with file.

Code:
# Write mode ('w'): Create a new file and write to it
with open('example.txt', 'w') as file:
file.write('This is a test.\n')

# Read mode ('r'): Read data from an existing file


with open('example.txt', 'r') as file:
content = file.read()
print(content)

# Append mode ('a'): Append data to an existing file


with open('example.txt', 'a') as file:
file.write('Appending more data.\n')

# Read mode with file pointer ('r+'): Read and write to an existing file
with open('example.txt', 'r+') as file:
content = file.read()
print(content)
file.write('Writing more data.')

# Read mode with file pointer ('r+'): Read and write to an existing file at a specific position
with open('example.txt', 'r+') as file:
file.seek(0, 2) # Move the file pointer to the end of the file
file.write('\nAdding at the end.')

# Read and write mode ('w+'): Create a new file and read/write to it
with open('example2.txt', 'w+') as file:
file.write('Writing and reading.\n')
file.seek(0) # Move the file pointer to the beginning of the file
content = file.read()

UTU/CGPIT/IT/SEM-4/Programming with Python 33


Enrollment No: 202203103510061

print(content)
# Append and read mode ('a+'): Open an existing file for reading and writing (appending)
with open('example2.txt', 'a+') as file:
file.write('Appending and reading.\n')
file.seek(0) # Move the file pointer to the beginning of the file
content = file.read()
print(content)

Output:

b) Reads data from text file in reverse order and write it into another
file.

Code:
# Reading data from a text file in reverse order and writing it into another file
def reverse_file_content():
with open("N1.txt", "r") as file:
lines = file.readlines()
with open("reversed_N2.txt", "w") as file:
for line in reversed(lines):
file.write(line)
# Read data from text file in reverse order and write it into another file
reverse_file_content()
print("Data from 'example.txt' has been written to 'reversed_demo_file.txt' in reverse
order.")

Output:

UTU/CGPIT/IT/SEM-4/Programming with Python 34


Enrollment No: 202203103510061

Practical-16

Aim: a. Write a python program that reads a text file and performs the
following.
- Write first N lines of source file into another file.
- Find current position of location pointer in file
- Reset location pointer to 5th character position of file.
b. Write a python program that reads a text file and performs the
following:
- Count the number of lines
- Count number of unique words
- Count occurrence of each word

a) Write a python program that reads a text file and performs the
following.
- Write first N lines of source file into another file.
- Find current position of location pointer in file
- Reset location pointer to 5th character position of file.

Code:
def process_text_file(example, destination_file, n_lines):
# Write first N lines of example file into another file
with open(example, "r") as f_source:
lines_to_write = [next(f_source) for _ in range(n_lines)]
with open(destination_file, "w") as f_dest:
f_dest.writelines(lines_to_write)

with open(example, "r") as f:


current_position = f.tell()

with open(example, "r+") as f:


f.seek(5)
fifth_character_position = f.tell()
return current_position,fifth_character_position

if __name__ == "__main__":

UTU/CGPIT/IT/SEM-4/Programming with Python 35


Enrollment No: 202203103510061

example = "example.txt"
destination_file = "destination.txt"
n_lines = 3
current_pos, fifth_char_pos = process_text_file(example, destination_file, n_lines)
print("Current position of location pointer in file:", current_pos)
print("Reset location pointer to 5th character position of file:", fifth_char_pos)

Output:

b) Write a python program that reads a text file and performs the
following:
- Count the number of lines
- Count number of unique words
- Count occurrence of each word

Code:
def count_lines(file_path):
with open(file_path, 'r') as file:
line_count = sum(1 for _ in file)
return line_count

def count_unique_words(file_path):
unique_words = set()
with open(file_path, 'r') as file:
for line in file:
words = line.split()
unique_words.update(words)
return len(unique_words)

def count_word_occurrences(file_path):
word_occurrences = {}
with open(file_path, 'r') as file:
for line in file:
words = line.split()
for word in words:
word_occurrences[word] = word_occurrences.get(word, 0) + 1

UTU/CGPIT/IT/SEM-4/Programming with Python 36


Enrollment No: 202203103510061

return word_occurrences

if __name__ == "__main__":
file_path = "example.txt" # Replace with your file path
num_lines = count_lines(file_path)
print("Number of lines:", num_lines)
num_unique_words = count_unique_words(file_path)
print("Number of unique words:", num_unique_words)
word_occurrences = count_word_occurrences(file_path)
print("Word occurrences:")
for word, count in word_occurrences.items():
print(word, ":", count)

Output:

Practical-17

UTU/CGPIT/IT/SEM-4/Programming with Python 37


Enrollment No: 202203103510061

Aim: a. Write a python program that will call respective exception errors
in the following cases:

- if number is divided by zero


- if import module is not existed
- if file cannot be open
- if there is a python syntax error
b. Write a python code that will raise an exception if the user’s age is
not eligible for voting.

a) Write a python program that will call respective exception errors in


the following cases:
- if number is divided by zero
- if import module is not existed
- if file cannot be open
- if there is a python syntax error

Code:
#Case 1
try:
numerator = 10
denominator = 0
result = numerator / denominator
except ZeroDivisionError as e:
print("Error:", e)
# Case 2
try:
with open("python2.txt", "r") as file:
content = file.read()
except FileNotFoundError as e:
print("Error:", e)
# Case 3
code = print("Hello, World"

try:
compiled_code = compile(code, "<string>", "exec")
exec(compiled_code)

UTU/CGPIT/IT/SEM-4/Programming with Python 38


Enrollment No: 202203103510061

except SyntaxError as e:
print("SyntaxError:", e)

Output:

b) Write a python code that will raise an exception if the user’s age is not
eligible for voting.

Code:
def check_voting_eligibility(age):
if age < 18:
raise ValueError("Sorry, you are not eligible for voting.")
if __name__ == "__main__":
try:
age = int(input("Please enter your age: "))
check_voting_eligibility(age)
print("You are eligible for voting!")
except ValueError as ve:
print(ve)

Output:

Practical-18

UTU/CGPIT/IT/SEM-4/Programming with Python 39


Enrollment No: 202203103510061

Aim: Use SQLite3 in python to perform the following tasks:


i. Create a database “Course” and a table“Result”.
ii. Insert Student_Name, Enrolment_No, Semester, Branch,
Subject and Grade of student into table “Result”.
iii. Update Subject of Students in 4th semester from OS to FOS.
iv. Delete all students entry having FF grade.
v. Display all students entry in given format:
Student_Name: XXXXX
Enrolment_No: XXXXX
Semester: X ,Branch: XX
Subject: XXXXXX
Grade: XX

Code:
import sqlite3
# Create a connection to the database (or create it if it doesn't exist)
conn = sqlite3.connect('Course.db')
# Create a cursor object to execute SQL commands
cursor = conn.cursor()

# Task i: Create a database "Course" and a table "Result"


cursor.execute('''
CREATE TABLE IF NOT EXISTS Result (
Student_Name TEXT,
Enrolment_No TEXT PRIMARY KEY,
Semester INTEGER,
Branch TEXT,
Subject TEXT,
Grade TEXT
)
''')

# Task ii: Insert data into the "Result" table


students_data = [
('Alice', 'E001', 4, 'CS', 'OS', 'A'),
('Bob', 'E002', 3, 'IT', 'DBMS', 'B'),
('Charlie', 'E003', 4, 'EE', 'OS', 'FF'),

UTU/CGPIT/IT/SEM-4/Programming with Python 40


Enrollment No: 202203103510061

('David', 'E004', 4, 'ME', 'Maths', 'C'),


]
cursor.executemany('''
INSERT INTO Result (Student_Name, Enrolment_No, Semester, Branch, Subject, Grade)
VALUES (?, ?, ?, ?, ?, ?) ''', students_data)

# Task iii: Update subject of students in 4th semester from OS to FOS


cursor.execute('''
UPDATE Result
SET Subject = 'FOS'
WHERE Semester = 4 AND Subject = 'OS'
''')
# Task iv: Delete all students entries having FF grade
cursor.execute('''
DELETE FROM Result
WHERE Grade = 'FF'
''')

# Task v: Display all students entries


cursor.execute('''
SELECT Student_Name, Enrolment_No, Semester, Branch, Subject, Grade
FROM Result
''')

# Fetch and display the data in the given format


print("Displaying all students entries:")
for row in cursor.fetchall():
print("Student_Name: {}\nEnrolment_No: {}\nSemester: {}, Branch: {} \nSubject:{}\
nGrade: {}\n".format(row[0],row[1],row[2],row[3],row[4],row[5]))

# Commit the changes and close the connection


conn.commit()
conn.close()

Output:

UTU/CGPIT/IT/SEM-4/Programming with Python 41


Enrollment No: 202203103510061

UTU/CGPIT/IT/SEM-4/Programming with Python 42

You might also like