diff --git a/1 File handle/File handle binary/.env b/1 File handle/File handle binary/.env new file mode 100644 index 00000000000..ab3d7291cb4 --- /dev/null +++ b/1 File handle/File handle binary/.env @@ -0,0 +1 @@ +STUDENTS_RECORD_FILE= "student_records.pkl" \ No newline at end of file diff --git a/1 File handle/File handle binary/Deleting record in a binary file.py b/1 File handle/File handle binary/Deleting record in a binary file.py deleted file mode 100644 index 72323f84120..00000000000 --- a/1 File handle/File handle binary/Deleting record in a binary file.py +++ /dev/null @@ -1,17 +0,0 @@ -import pickle - - -def bdelete(): - # Opening a file & loading it - with open("studrec.dat", "rb") as F: - stud = pickle.load(F) - print(stud) - - # Deleting the Roll no. entered by user - rno = int(input("Enter the Roll no. to be deleted: ")) - with open("studrec.dat", "wb") as F: - rec = [i for i in stud if i[0] != rno] - pickle.dump(rec, F) - - -bdelete() diff --git a/1 File handle/File handle binary/Update a binary file2.py b/1 File handle/File handle binary/Update a binary file2.py index c1eee7d3800..d256c7c805b 100644 --- a/1 File handle/File handle binary/Update a binary file2.py +++ b/1 File handle/File handle binary/Update a binary file2.py @@ -27,3 +27,7 @@ def update(): update() + +# ! Instead of AB use WB? +# ! It may have memory limits while updating large files but it would be good +# ! Few lakhs records would be fine and wouln't create any much of a significant issues diff --git a/1 File handle/File handle binary/delete.py b/1 File handle/File handle binary/delete.py new file mode 100644 index 00000000000..c2175469522 --- /dev/null +++ b/1 File handle/File handle binary/delete.py @@ -0,0 +1,44 @@ +import logging +import os +import pickle + +from dotenv import load_dotenv + +base = os.path.dirname(__file__) +load_dotenv(os.path.join(base, ".env")) + +logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") +student_record = os.getenv("STUDENTS_RECORD_FILE") + + +def b_read(): + # Opening a file & loading it + if not os.path.exists(student_record): + logging.warning("File not found") + return + + with open(student_record, "rb") as F: + student = pickle.load(F) + logging.info("File opened successfully") + logging.info("Records in the file are:") + for i in student: + logging.info(i) + + +def b_modify(): + # Deleting the Roll no. entered by user + if not os.path.exists(student_record): + logging.warning("File not found") + return + roll_no = int(input("Enter the Roll No. to be deleted: ")) + student = 0 + with open(student_record, "rb") as F: + student = pickle.load(F) + + with open(student_record, "wb") as F: + rec = [i for i in student if i[0] != roll_no] + pickle.dump(rec, F) + + +b_read() +b_modify() diff --git a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py index 60207f85d7e..8b6d120cbf7 100644 --- a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py +++ b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py @@ -1,50 +1,53 @@ """Amit is a monitor of class XII-A and he stored the record of all -the students of his class in a file named “class.dat”. +the students of his class in a file named “student_records.pkl”. Structure of record is [roll number, name, percentage]. His computer teacher has assigned the following duty to Amit Write a function remcount( ) to count the number of students who need remedial class (student who scored less than 40 percent) +and find the top students of the class. - +We have to find weak students and bright students. """ -# also find no. of children who got top marks + +## Find bright students and weak students + +from dotenv import load_dotenv +import os + +base = os.path.dirname(__file__) +load_dotenv(os.path.join(base, ".env")) +student_record = os.getenv("STUDENTS_RECORD_FILE") import pickle +import logging + +# Define logger with info +# import polar -list = [ - [1, "Ramya", 30], - [2, "vaishnavi", 60], - [3, "anuya", 40], - [4, "kamala", 30], - [5, "anuraag", 10], - [6, "Reshi", 77], - [7, "Biancaa.R", 100], - [8, "sandhya", 65], -] -with open("class.dat", "ab") as F: - pickle.dump(list, F) - F.close() +## ! Unoptimised rehne de abhi ke liye def remcount(): - with open("class.dat", "rb") as F: + with open(student_record, "rb") as F: val = pickle.load(F) count = 0 + weak_students = [] - for i in val: - if i[2] <= 40: - print(f"{i} eligible for remedial") + for student in val: + if student[2] <= 40: + print(f"{student} eligible for remedial") + weak_students.append(student) count += 1 - print(f"the total number of students are {count}") + print(f"the total number of weak students are {count}") + print(f"The weak students are {weak_students}") - -remcount() + # ! highest marks is the key here first marks def firstmark(): - with open("class.dat", "rb") as F: + with open(student_record, "rb") as F: val = pickle.load(F) count = 0 main = [i[2] for i in val] @@ -52,17 +55,12 @@ def firstmark(): top = max(main) print(top, "is the first mark") - F.seek(0) for i in val: if top == i[2]: print(f"{i}\ncongrats") count += 1 - - print("the total number of students who secured top marks are", count) + print("The total number of students who secured top marks are", count) +remcount() firstmark() - -with open("class.dat", "rb") as F: - val = pickle.load(F) - print(val) diff --git a/1 File handle/File handle binary/File handle binary read (record in non list form).py b/1 File handle/File handle binary/read.py similarity index 95% rename from 1 File handle/File handle binary/File handle binary read (record in non list form).py rename to 1 File handle/File handle binary/read.py index 45321e20600..9c69281b4bf 100644 --- a/1 File handle/File handle binary/File handle binary read (record in non list form).py +++ b/1 File handle/File handle binary/read.py @@ -1,22 +1,22 @@ -import pickle - - -def binary_read(): - with open("studrec.dat", "rb") as b: - stud = pickle.load(b) - print(stud) - - # prints the whole record in nested list format - print("contents of binary file") - - for ch in stud: - print(ch) # prints one of the chosen rec in list - - rno = ch[0] - rname = ch[1] # due to unpacking the val not printed in list format - rmark = ch[2] - - print(rno, rname, rmark, end="\t") - - -binary_read() +import pickle + + +def binary_read(): + with open("studrec.dat", "rb") as b: + stud = pickle.load(b) + print(stud) + + # prints the whole record in nested list format + print("contents of binary file") + + for ch in stud: + print(ch) # prints one of the chosen rec in list + + rno = ch[0] + rname = ch[1] # due to unpacking the val not printed in list format + rmark = ch[2] + + print(rno, rname, rmark, end="\t") + + +binary_read() diff --git a/1 File handle/File handle binary/search record in binary file.py b/1 File handle/File handle binary/search record in binary file.py index 80d2071134e..a6529e15240 100644 --- a/1 File handle/File handle binary/search record in binary file.py +++ b/1 File handle/File handle binary/search record in binary file.py @@ -1,20 +1,21 @@ # binary file to search a given record import pickle +from dotenv import load_dotenv -def binary_search(): - with open("studrec.dat", "rb") as F: +def search(): + with open("student_records.pkl", "rb") as F: # your file path will be different - search = 0 + search = True rno = int(input("Enter the roll number of the student")) for i in pickle.load(F): if i[0] == rno: print(f"Record found successfully\n{i}") - search = 1 + search = False - if search == 0: + if search: print("Sorry! record not found") diff --git a/1 File handle/File handle binary/update2.py b/1 File handle/File handle binary/update2.py new file mode 100644 index 00000000000..001b6d5b660 --- /dev/null +++ b/1 File handle/File handle binary/update2.py @@ -0,0 +1,32 @@ +# Updating records in a binary file +# ! Have a .env file please +import pickle +import os +from dotenv import load_dotenv + +base = os.path.dirname(__file__) +load_dotenv(os.path.join(base, ".env")) +student_record = os.getenv("STUDENTS_RECORD_FILE") + + +def update(): + with open(student_record, "rb") as F: + S = pickle.load(F) + found = False + rno = int(input("enter the roll number you want to update")) + + for i in S: + if rno == i[0]: + print(f"the currrent name is {i[1]}") + i[1] = input("enter the new name") + found = True + break + + if found: + print("Record not found") + + with open(student_record, "wb") as F: + pickle.dump(S, F) + + +update() diff --git a/file_handle/File handle binary/.env b/file_handle/File handle binary/.env new file mode 100644 index 00000000000..ab3d7291cb4 --- /dev/null +++ b/file_handle/File handle binary/.env @@ -0,0 +1 @@ +STUDENTS_RECORD_FILE= "student_records.pkl" \ No newline at end of file diff --git a/file_handle/File handle binary/Update a binary file2.py b/file_handle/File handle binary/Update a binary file2.py new file mode 100644 index 00000000000..37b5a24e459 --- /dev/null +++ b/file_handle/File handle binary/Update a binary file2.py @@ -0,0 +1,40 @@ +# updating records in a binary file + +import pickle +import os + +base = os.path.dirname(__file__) +from dotenv import load_dotenv + +load_dotenv(os.path.join(base, ".env")) +student_record = os.getenv("STUDENTS_RECORD_FILE") + +## ! Understand how pandas works internally + + +def update(): + with open(student_record, "rb") as File: + value = pickle.load(File) + found = False + roll = int(input("Enter the roll number of the record")) + + for i in value: + if roll == i[0]: + print(f"current name {i[1]}") + print(f"current marks {i[2]}") + i[1] = input("Enter the new name") + i[2] = int(input("Enter the new marks")) + found = True + + if not found: + print("Record not found") + + with open(student_record, "wb") as File: + pickle.dump(value, File) + + +update() + +# ! Instead of AB use WB? +# ! It may have memory limits while updating large files but it would be good +# ! Few lakhs records would be fine and wouldn't create any much of a significant issues diff --git a/file_handle/File handle binary/delete.py b/file_handle/File handle binary/delete.py new file mode 100644 index 00000000000..c2175469522 --- /dev/null +++ b/file_handle/File handle binary/delete.py @@ -0,0 +1,44 @@ +import logging +import os +import pickle + +from dotenv import load_dotenv + +base = os.path.dirname(__file__) +load_dotenv(os.path.join(base, ".env")) + +logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") +student_record = os.getenv("STUDENTS_RECORD_FILE") + + +def b_read(): + # Opening a file & loading it + if not os.path.exists(student_record): + logging.warning("File not found") + return + + with open(student_record, "rb") as F: + student = pickle.load(F) + logging.info("File opened successfully") + logging.info("Records in the file are:") + for i in student: + logging.info(i) + + +def b_modify(): + # Deleting the Roll no. entered by user + if not os.path.exists(student_record): + logging.warning("File not found") + return + roll_no = int(input("Enter the Roll No. to be deleted: ")) + student = 0 + with open(student_record, "rb") as F: + student = pickle.load(F) + + with open(student_record, "wb") as F: + rec = [i for i in student if i[0] != roll_no] + pickle.dump(rec, F) + + +b_read() +b_modify() diff --git a/file_handle/File handle binary/question 1 (elegible for remedial, top marks).py b/file_handle/File handle binary/question 1 (elegible for remedial, top marks).py new file mode 100644 index 00000000000..27a29f887dc --- /dev/null +++ b/file_handle/File handle binary/question 1 (elegible for remedial, top marks).py @@ -0,0 +1,66 @@ +"""Amit is a monitor of class XII-A and he stored the record of all +the students of his class in a file named “student_records.pkl”. +Structure of record is [roll number, name, percentage]. His computer +teacher has assigned the following duty to Amit + +Write a function remcount( ) to count the number of students who need + remedial class (student who scored less than 40 percent) +and find the top students of the class. + +We have to find weak students and bright students. +""" + +## Find bright students and weak students + +from dotenv import load_dotenv +import os + +base = os.path.dirname(__file__) +load_dotenv(os.path.join(base, ".env")) +student_record = os.getenv("STUDENTS_RECORD_FILE") + +import pickle +import logging + +# Define logger with info +# import polar + + +## ! Unoptimised rehne de abhi ke liye + + +def remcount(): + with open(student_record, "rb") as F: + val = pickle.load(F) + count = 0 + weak_students = [] + + for student in val: + if student[2] <= 40: + print(f"{student} eligible for remedial") + weak_students.append(student) + count += 1 + print(f"the total number of weak students are {count}") + print(f"The weak students are {weak_students}") + + # ! highest marks is the key here first marks + + +def firstmark(): + with open(student_record, "rb") as F: + val = pickle.load(F) + count = 0 + main = [i[2] for i in val] + + top = max(main) + print(top, "is the first mark") + + for i in val: + if top == i[2]: + print(f"{i}\ncongrats") + count += 1 + print("The total number of students who secured top marks are", count) + + +remcount() +firstmark() diff --git a/file_handle/File handle binary/read.py b/file_handle/File handle binary/read.py new file mode 100644 index 00000000000..9c69281b4bf --- /dev/null +++ b/file_handle/File handle binary/read.py @@ -0,0 +1,22 @@ +import pickle + + +def binary_read(): + with open("studrec.dat", "rb") as b: + stud = pickle.load(b) + print(stud) + + # prints the whole record in nested list format + print("contents of binary file") + + for ch in stud: + print(ch) # prints one of the chosen rec in list + + rno = ch[0] + rname = ch[1] # due to unpacking the val not printed in list format + rmark = ch[2] + + print(rno, rname, rmark, end="\t") + + +binary_read() diff --git a/file_handle/File handle binary/search record in binary file.py b/file_handle/File handle binary/search record in binary file.py new file mode 100644 index 00000000000..a3b89e69c87 --- /dev/null +++ b/file_handle/File handle binary/search record in binary file.py @@ -0,0 +1,22 @@ +# binary file to search a given record + +import pickle +from dotenv import load_dotenv + + +def search(): + with open("student_records.pkl", "rb") as F: + # your file path will be different + search = True + rno = int(input("Enter the roll number of the student")) + + for i in pickle.load(F): + if i[0] == rno: + print(f"Record found successfully\n{i}") + search = False + + if search: + print("Sorry! record not found") + + +search() diff --git a/1 File handle/File handle binary/Update a binary file.py b/file_handle/File handle binary/update2.py similarity index 64% rename from 1 File handle/File handle binary/Update a binary file.py rename to file_handle/File handle binary/update2.py index b72154345ae..ecb55168906 100644 --- a/1 File handle/File handle binary/Update a binary file.py +++ b/file_handle/File handle binary/update2.py @@ -1,30 +1,30 @@ -# Updating records in a binary file - -import pickle - - -def update(): - with open("class.dat", "rb+") as F: - S = pickle.load(F) - found = False - rno = int(input("enter the roll number you want to update")) - - for i in S: - if rno == i[0]: - print(f"the currrent name is {i[1]}") - i[1] = input("enter the new name") - found = True - break - - if found: - print("Record not found") - - else: - F.seek(0) - pickle.dump(S, F) - - -update() - -with open("class.dat", "rb") as F: - print(pickle.load(F)) +import pickle +import os +from dotenv import load_dotenv + +base = os.path.dirname(__file__) +load_dotenv(os.path.join(base, ".env")) +student_record = os.getenv("STUDENTS_RECORD_FILE") + + +def update(): + with open(student_record, "rb") as F: + S = pickle.load(F) + found = False + rno = int(input("enter the roll number you want to update")) + + for i in S: + if rno == i[0]: + print(f"the currrent name is {i[1]}") + i[1] = input("enter the new name") + found = True + break + + if found: + print("Record not found") + + with open(student_record, "wb") as F: + pickle.dump(S, F) + + +update() diff --git a/file_handle/File handle text/counter.py b/file_handle/File handle text/counter.py new file mode 100644 index 00000000000..0cf3d03819a --- /dev/null +++ b/file_handle/File handle text/counter.py @@ -0,0 +1,44 @@ +""" +Class resposible for counting words for different files: +- Reduce redundant code +- Easier code management/debugging +- Code readability +""" + +## ! Is there any other way than doing it linear? + + +## ! What will be test cases of it? +# ! Please do let me know. +## ! Can add is digit, isspace methods too later on. +# ! Based on requirements of it + + + +## ! The questions are nothing but test-cases +## ! Make a test thing and handle it. +# does it count only alphabets or numerics too? +# ? what about other characters? +class Counter: + def __init__(self, text: str) -> None: + self.text = text + # Define the initial count of the lower and upper case. + self.count_lower = 0 + self.count_upper = 0 + self.compute() + + def compute(self) -> None: + for char in self.text: + if char.islower(): + self.count_lower += 1 + elif char.isupper(): + self.count_upper += 1 + + def get_total_lower(self) -> int: + return self.count_lower + + def get_total_upper(self) -> int: + return self.count_upper + + def get_total_chars(self) -> int: + return self.count_lower + self.count_upper diff --git a/file_handle/File handle text/file handle 12 length of line in text file.py b/file_handle/File handle text/file handle 12 length of line in text file.py new file mode 100644 index 00000000000..1280c21b245 --- /dev/null +++ b/file_handle/File handle text/file handle 12 length of line in text file.py @@ -0,0 +1,38 @@ +import os +import time + +file_name = input("Enter the file name to create:- ") + +print(file_name) + + +def write_to_file(file_name): + if os.path.exists(file_name): + print(f"Error: {file_name} already exists.") + return + + with open(file_name, "a") as F: + while True: + text = input("enter any text to add in the file:- ") + F.write(f"{text}\n") + choice = input("Do you want to enter more, y/n").lower() + if choice == "n": + break + + +def longlines(): + with open(file_name, encoding="utf-8") as F: + lines = F.readlines() + lines_less_than_50 = list(filter(lambda line: len(line) < 50, lines)) + + if not lines_less_than_50: + print("There is no line which is less than 50") + else: + for i in lines_less_than_50: + print(i, end="\t") + + +if __name__ == "__main__": + write_to_file(file_name) + time.sleep(1) + longlines() diff --git a/file_handle/File handle text/happy.txt b/file_handle/File handle text/happy.txt new file mode 100644 index 00000000000..ce9edea82d1 --- /dev/null +++ b/file_handle/File handle text/happy.txt @@ -0,0 +1,11 @@ +hello how are you +what is your name +do not worry everything is alright +everything will be alright +please don't lose hope +Wonders are on the way +Take a walk in the park +At the end of the day you are more important than anything else. +Many moments of happiness are waiting +You are amazing! +If you truly believe. \ No newline at end of file diff --git a/file_handle/File handle text/input,output and error streams.py b/file_handle/File handle text/input,output and error streams.py new file mode 100644 index 00000000000..a83319f8b5a --- /dev/null +++ b/file_handle/File handle text/input,output and error streams.py @@ -0,0 +1,16 @@ +# practicing with streams +import sys + +sys.stdout.write("Enter the name of the file") +file = sys.stdin.readline() + +with open( + file.strip(), +) as F: + while True: + ch = F.readlines() + for i in ch: # ch is the whole file,for i in ch gives lines, for j in i gives letters,for j in i.split gives words + print(i, end="") + else: + sys.stderr.write("End of file reached") + break diff --git a/file_handle/File handle text/question 2.py b/file_handle/File handle text/question 2.py new file mode 100644 index 00000000000..58a69f0b27d --- /dev/null +++ b/file_handle/File handle text/question 2.py @@ -0,0 +1,32 @@ +"""Write a method/function DISPLAYWORDS() in python to read lines + from a text file STORY.TXT, + using read function +and display those words, which are less than 4 characters.""" + +print("Hey!! You can print the word which are less then 4 characters") + + +def display_words(file_path): + try: + with open(file_path) as F: + words = F.read().split() + words_less_than_40 = list(filter(lambda word: len(word) < 4, words)) + + for word in words_less_than_40: + print(word) + + return ( + "The total number of the word's count which has less than 4 characters", + (len(words_less_than_40)), + ) + + except FileNotFoundError: + print("File not found") + + +print("Just need to pass the path of your file..") + +file_path = input("Please, Enter file path: ") + +if __name__ == "__main__": + print(display_words(file_path)) diff --git a/file_handle/File handle text/question 5.py b/file_handle/File handle text/question 5.py new file mode 100644 index 00000000000..1c3ec52935e --- /dev/null +++ b/file_handle/File handle text/question 5.py @@ -0,0 +1,40 @@ +"""Write a function in python to count the number of lowercase +alphabets present in a text file “happy.txt""" + +import time +import os +from counter import Counter + +print( + "You will see the count of lowercase, uppercase and total count of alphabets in provided file.." +) + + +file_path = input("Please, Enter file path: ") + +if os.path.exists(file_path): + print("The file exists and this is the path:\n", file_path) + + +def lowercase(file_path): + try: + with open(file_path) as F: + word_counter = Counter(F.read()) + + print( + f"The total number of lower case letters are {word_counter.get_total_lower()}" + ) + time.sleep(0.5) + print( + f"The total number of upper case letters are {word_counter.get_total_upper()}" + ) + time.sleep(0.5) + print(f"The total number of letters are {word_counter.get_total()}") + time.sleep(0.5) + + except FileNotFoundError: + print("File is not exist.. Please check AGAIN") + + +if __name__ == "__main__": + lowercase(file_path) diff --git a/file_handle/File handle text/question 6.py b/file_handle/File handle text/question 6.py new file mode 100644 index 00000000000..e8fde939b4c --- /dev/null +++ b/file_handle/File handle text/question 6.py @@ -0,0 +1,21 @@ +"""Write a function in python to count the number of lowercase +alphabets present in a text file “happy.txt”""" + +from counter import Counter + + +def lowercase(): + with open("happy.txt") as F: + word_counter = Counter(F.read()) + + print( + f"The total number of lower case letters are {word_counter.get_total_lower()}" + ) + print( + f"The total number of upper case letters are {word_counter.get_total_upper()}" + ) + print(f"The total number of letters are {word_counter.get_total()}") + + +if __name__ == "__main__": + lowercase() diff --git a/file_handle/File handle text/question3.py b/file_handle/File handle text/question3.py new file mode 100644 index 00000000000..7a771e8994d --- /dev/null +++ b/file_handle/File handle text/question3.py @@ -0,0 +1,47 @@ +"""Write a user-defined function named count() that will read +the contents of text file named “happy.txt” and count +the number of lines which starts with either “I‟ or “M‟.""" + +import os +import time + +file_name = input("Enter the file name to create:- ") + +# step1: +print(file_name) + + +def write_to_file(file_name): + if os.path.exists(file_name): + print(f"Error: {file_name} already exists.") + + else: + with open(file_name, "a") as F: + while True: + text = input("enter any text") + F.write(f"{text}\n") + + if input("do you want to enter more, y/n").lower() == "n": + break + + +# step2: +def check_first_letter(): + with open(file_name) as F: + lines = F.read().split() + + # store all starting letters from each line in one string after converting to lower case + first_letters = "".join([line[0].lower() for line in lines]) + + count_i = first_letters.count("i") + count_m = first_letters.count("m") + + print( + f"The total number of sentences starting with I or M are {count_i + count_m}" + ) + + +if __name__ == "__main__": + write_to_file(file_name) + time.sleep(1) + check_first_letter() diff --git a/file_handle/File handle text/special symbol after word.py b/file_handle/File handle text/special symbol after word.py new file mode 100644 index 00000000000..6e44cc99321 --- /dev/null +++ b/file_handle/File handle text/special symbol after word.py @@ -0,0 +1,11 @@ +with open("happy.txt", "r") as F: + # method 1 + for i in F.read().split(): + print(i, "*", end="") + print("\n") + + # method 2 + F.seek(0) + for line in F.readlines(): + for word in line.split(): + print(word, "*", end="") diff --git a/file_handle/File handle text/story.txt b/file_handle/File handle text/story.txt new file mode 100644 index 00000000000..c9f59eb01c6 --- /dev/null +++ b/file_handle/File handle text/story.txt @@ -0,0 +1,5 @@ +once upon a time there was a king. +he was powerful and happy. +he +all the flowers in his garden were beautiful. +he lived happily ever after. \ No newline at end of file