Skip to content
Snippets Groups Projects
Commit 769191f9 authored by rizan-kc's avatar rizan-kc
Browse files

feat: Added Week5 and Week6 tasks

parent d79f1614
No related branches found
No related tags found
No related merge requests found
Hello, My name is Rizan K.C.
Let's explore the file handling
File handling is a concept in programming where we work with files.
\ No newline at end of file
Hello, My name is Rizan K.C.
Let's explore the file handling
File handling is a concept in programming where we work with files.
\ No newline at end of file
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
Rizan KC is a man.
\ No newline at end of file
Book ID,Title,Author,Is Issued
1,The Pursuit of Happyness,Chris Gardner,False
2,Rita Hayworth and Shawshank Redemption,Stephen King,False
3,Forrest Gump,Winston Groom,False
'''
The program has a class called Employee with different attributes.
This allows to add multiple employees data to be taken as input and save it in a csv file called
employees.csv
This data can also later be viewed to see the list of employees and their details.
'''
import csv
import os
class Employee:
'''
Class to represent an employee with their data
Attributes:
empid: identity of the employee, datatype = int
name: name of the employee, datatype = str
Address: Address of the employee, datatype = str
contact_number: Contact number of the employee, datatype = str
number_of_child: Number of children, datatype = int
salary: identity of the employee, dattype = int
Methods:
save_csv(): saves the data to a csv file named 'employees.csv'
'''
def __init__(self, id, name, address, contact, spouse, noc, salary):
self.empid = id
self.name = name
self.address = address
self.contact_number = contact
self.spouse_name = spouse
self.number_of_child = noc
self.salary = salary
def save_csv(self):
try:
file_exist = os.path.isfile("employees.csv")
with open("employees.csv",mode = "a", newline="") as csv_file:
lt = [self.empid,self.name,self.address,self.contact_number,self.spouse_name,self.number_of_child,self.salary]
writer = csv.writer(csv_file)
if not file_exist:
writer.writerow(["Employee ID","Name","Address","Contact","Spouse","Children","Salary"])
writer.writerow(lt)
print("File Saved Successfully!")
except Exception as e:
return ("Error:",e)
def read_csv():
try:
file_exist = os.path.isfile("employees.csv")
if file_exist:
with open("employees.csv",mode = "r") as csv_file:
content = csv.reader(csv_file)
rows = list(content)
if rows:
col_width = [max(len(item) for item in col) for col in zip(*rows)]
for row in rows:
formatted_row = " | ".join(item.ljust(col_width[i]) for i, item in enumerate(row))
print(formatted_row)
except Exception as e:
print("Error:",e)
def input_data():
try:
id = int(input("Enter your ID: "))
n = input("Enter your name: ")
a = input("Enter your address: ")
c = input("Enter your contact number: ")
s = input("Enter your spouse name: ")
nc = int(input("Enter the number of children, if no children's enter 0: "))
sa = int(input("Enter your salary:"))
return [id, n, a, c, s, nc, sa]
except:
return "Invalid Input"
print(__doc__)
while True:
print(f"{'Employment Directory':>75}")
print(f"{'1. Enter your Credentials':>77} ")
print(f"{'2. List the Credentials':>77} ")
print(f"{'3. Exit':>70}")
init_ch = int(input("Enter 1,2,3 based on your preference: "))
if init_ch == 1:
x = input_data()
if isinstance(x, list):
emp = Employee(*x)
ch_save = input("Do you want to save this in a file? ")
if ch_save == 'Y' or ch_save == 'y':
emp.save_csv()
elif init_ch == 2:
read_csv()
elif init_ch == 3:
print("Exiting the program.")
break
else:
print("Invalid Option. Try again!")
class Student:
'''
This class represents the blueprint for student object.
Attributes:
id: The id of the student, datatype = int
name: The full name of the student, datatype = str
address: The address of the student, datatype = str
admission_year: The year the student was admitted, datatype = int
level: The level/year of the student, datatype = int
section: The section assigned to the student, datatype = str
Methods:
display(): This method displays all the attributes of the Student
'''
def __init__(self, id, name, address, admit_year, level, section):
self.id = id
self.name = name
self.address = address
self.admission_year = admit_year
self.level = level
self.section = section
def display(self):
print(f"Id: {self.id}")
print(f"Name: {self.name}")
print(f"Address: {self.address}")
print(f"Admission Year: {self.admission_year}")
print(f"Level: {self.level}")
print(f"Section: {self.section}")
#print(Student.__doc__)
s_id = int(input("Enter your Student ID: "))
name = input("Enter your Name: ")
address = input("Enter your Address: ")
admit = int(input("Enter Admission Year: "))
level = int(input("Enter Level: "))
sec = input("Enter Section: ")
s1 = Student(s_id,name,address,admit,level,sec)
print()
s1.display()
'''
This program copies the content of one file to another.
For this, two files are used: File1.txt and File2.txt
File1.txt is used for copying the content.
File2.txt is the file to paste the copied content from File1.txt
'''
x = open("File1.txt","r")
content = x.read()
print("The content inside the File1.txt is:")
print(content)
x.close()
print()
z = open("File2.txt","r")
content_file2 = z.read()
print("The content inside the File2.txt is:")
print(content_file2)
z.close()
# Pasting the content of other file.
y = open("File2.txt","w")
y.write(content)
y.close()
# Reading to verify if the content are copied or not!
z = open("File2.txt","r")
content_copied = z.read()
print("The content inside the File2.txt after pasting is:")
print(content_copied)
z.close()
\ No newline at end of file
'''
This program conts the occurence of each word in a file.
'''
with open("File3.txt","r") as f:
content = f.read()
content = content.split()
content_dic = dict()
for x in content:
if x in content_dic:
content_dic[x] += 1
else:
content_dic[x] = 1
print(content_dic)
'''
This program counts the number of lines, words and characters present in a text file.
'''
with open("File1.txt") as f:
#counts the number of line
lines = f.readlines()
print(f"The total number of lines in the file is {len(lines)}.")
#counts the number of words and characters
f.seek(0)
content = f.read()
words = content.split()
#words
print(f"The total number of words in the file is {len(words)}")
#characters
char = list(content)
print(f"The total number of characters in the file is {len(char)}.")
\ No newline at end of file
'''
This program reads a CSV file and display its contents in a tabular format.
'''
import csv
with open('kohli_ipl.csv','r') as f:
content = csv.reader(f)
rows = list(content)
if rows:
col_wid = [max(len(item) for item in col) for col in zip(*rows)]
for row in rows:
formatted_row = " | ".join(item.ljust(col_wid[i]) for i, item in enumerate(row))
print(formatted_row)
else:
print("Empty file.")
\ No newline at end of file
Employee ID,Name,Address,Contact,Spouse,Children,Salary
11210,Rizan KC,Dhungedhara,9819800000,Not Married,0,50000
11300,Prashish Sapkota,Mahalakshmi Kathmandu,9870010000,Krisha Sapkota,2,10000
11301,Younesh KC,Kupandole,9819800001,Divorced,8,10000
'''
This program replace a specific word with another word in a file with the help of file handling.
'''
def check_word(x , file):
'''
Checks if a given word exists in the file or not.
Parameter:
x: The word(str) to check
file: The filename including extension
Returns bool: True if x is in file otherwise bool: False.
'''
with open(file,'r') as f1:
c1 = f1.read()
return True if x in c1 else False
def replace_word(x, r ,file):
'''
Replaces all the occurences of a word in the given file with new word.
Argument:
x: Word to be replaced
r: Replacement Word
file: Filename where the replacement will happen
'''
with open(file,'r') as f2:
content = f2.read()
content = content.replace(x,r)
with open(file,'w') as f2:
f2.write(content)
while True:
x = input("Enter the word you want to replace: ")
f = input("Enter the file name you want to check, along with extension: ")
check = check_word(x,f)
if check == False:
continue
else:
r = input("Enter the new word: ")
replace_word(x, r, f)
break
match_no,runs
1,1
2,23
3,13
4,12
5,1
6,9
7,34
8,0
9,21
10,3
11,10
12,38
13,3
14,11
15,50
16,2
17,22
18,19
19,16
20,15
21,20
22,38
23,19
24,24
25,7
\ No newline at end of file
'''
This program is a simple library book management where a book can be issued, returned and search
the book. This uses OOP concepts along with file handling as well as try and except: error handling
'''
import csv
class Book:
'''
Class representing a book in the library.
Attributes:
book_id : Unique identifier for the book, datatype = int
title: Title of the book, dataatype = str
auth : Author of the book, datatype = str
is_issued : Whether the book is currently issued or available, datatype = bool
'''
def __init__(self, book_id, title, auth, is_issued=False):
self.book_id = book_id
self.title = title
self.auth = auth
self.is_issued = is_issued
def to_csv_row(self):
return [self.book_id, self.title, self.auth, str(self.is_issued)]
@classmethod
def from_csv_row(cls, row):
book_id, title, auth, issued_str = row
is_issued = issued_str.strip().lower() == "true"
return cls(book_id, title, auth, is_issued)
def __str__(self):
status = "Issued" if self.is_issued else "Available"
return f"BookID: {self.book_id}, Title: {self.title}, Author: {self.auth}, Status: {status}"
class Library:
def __init__(self, filename):
self.filename = filename
def load_books(self):
"""
Load books from the CSV file.
Returns a list of Book objects. If the file doesn't exist, returns an empty list.
"""
books = []
try:
with open(self.filename, mode='r', newline='', encoding='utf-8') as file:
reader = csv.reader(file)
header = next(reader, None)
for row in reader:
if row:
book = Book.from_csv_row(row)
books.append(book)
except FileNotFoundError:
print("Books file not found. A new file will be created on saving.")
except Exception as e:
print("Error loading books:", e)
return books
def save_books(self, books):
"""
Save the list of Book objects to the CSV file.
"""
try:
with open(self.filename, mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(["Book ID", "Title", "Author", "Is Issued"])
for book in books:
writer.writerow(book.to_csv_row())
except Exception as e:
print("Error saving books:", e)
def issue_books(self, book_id):
"""
Marks the specified book as issued if it is available.
"""
books = self.load_books()
found = False
for book in books:
if book.book_id.lower() == book_id.lower():
found = True
if not book.is_issued:
book.is_issued = True
print(f"Book '{book.title}' has been issued.")
else:
print(f"Book '{book.title}' is already issued.")
break
if not found:
print("Book not found.")
self.save_books(books)
def return_book(self, book_id):
"""
Marks the specified book as returned (available) if it was issued.
"""
books = self.load_books()
found = False
for book in books:
if book.book_id.lower() == book_id.lower():
found = True
if book.is_issued:
book.is_issued = False
print(f"Book '{book.title}' has been returned.")
else:
print(f"Book '{book.title}' was not issued.")
break
if not found:
print("Book not found.")
self.save_books(books)
def search_book(self, keyword):
"""
Searches for books with the keyword in Book ID, Title, or Author.
"""
books = self.load_books()
results = []
keyword = keyword.lower()
for book in books:
if (keyword in book.book_id.lower() or
keyword in book.title.lower() or
keyword in book.auth.lower()):
results.append(book)
if results:
print("\nSearch Results:")
for book in results:
print(book)
else:
print("No matching books found.")
filename = "books.csv"
library = Library(filename)
if not library.load_books():
print("No books were found in the library. Adding sample books...")
s_books = [Book("1", "The Pursuit of Happyness", "Chris Gardner"),
Book("2", "Rita Hayworth and Shawshank Redemption", "Stephen King"),
Book("3", "Forrest Gump", "Winston Groom")
]
library.save_books(s_books)
while True:
print("\n=== Library Book Management ===")
print("1. Issue the books")
print("2. Return books")
print("3. Search books")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == "1":
book_id = input("Enter the Book ID to issue: ")
library.issue_books(book_id)
elif choice == "2":
book_id = input("Enter the Book ID to return: ")
library.return_book(book_id)
elif choice == "3":
keyword = input("Enter keyword to search (Book ID, Title, or Author): ")
library.search_book(keyword)
elif choice == "4":
print("Exiting the System.")
break
else:
print("Invalid choice. Please select a valid option.")
File added
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment