FILE HANDLING in Python (Text File, Binary File, CSV File) Grade 12 Computer Science CBSE Syllabus File Handling in Python File handling: Need for a data file, Types of file: Text files, Binary files and CSV (Comma separated values) files. ● Text File: Basic operations on a text file: Open (filename – absolute or relative path, mode) / Close a text file, Reading and Manipulation of data from a text file, Appending data into a text file, standard input / output and error streams, relative and absolute paths. ● Binary File: Basic operations on a binary file: Open (filename – absolute or relative path, mode) / Close a binary file, Pickle Module –methods load and dump; Read, Write/Create, Search, Append and Update operations in a binary file. ● CSV File: Import csv module, functions – Open / Close a csv file, Read from a csv file and Write into a csv file using csv.reader ( ) and csv.writerow( ). INTRODUCTION: • File:- A file is a collection of related data stored in a particular area on the disk. • Stream: - It refers to a sequence of bytes. File handling is an important part of any web application. Data Files: The data files that store data pertaining to specific application, for later use. Data files can be stored in two ways: 1. Text Files: Text files are structured as a sequence of lines, where each line includes a sequence of characters. 2. Binary Files : A binary file is any type of file that is not a text file. Opening and closing a file: Opening a file: To work with a file, first of all you have to open the file. To open a file in python, we use open( ) function. The open( ) function takes two parameters; filename, and mode. open( ) function returns a file object. Syntax: file_objectname= open(filename, mode) Example: To open a file for reading it is enough to specify the name of the file: f = open("book.txt") The code above is the same as: f = open("book.txt", "rt") Where "r" for read mode, and "t" for text are the default values, you do not need to specify them. Closing a file: After performing the operations, the file has to be closed. For this, a close( ) function is used to close a file. Syntax: File_objectname.close( ) File Modes: Mode Description r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode. r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. File Modes: Mode Description w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. In addition you can specify if the file should be handled as binary or text mode: “t” – Text-Default value. Text mode “b” – Binary- Binary Mode (e.g. images) WORKING WITH TEXT FILES: Basic operations with files: a. Read the data from a file b. Write the data to a file c. Append the data to a file d. Delete a file a. Read the data from a file: There are 3 types of functions to read data from a file. ❖ read( ) : reads n bytes. if no n is specified, reads the entire file. ❖ readline( ) : Reads a line. if n is specified, reads n bytes. ❖ readlines( ): Reads all lines and returns a list. Steps to read data from a file: • Create and Open a file using open( ) function • use the read( ), readline( ) or readlines( ) function • print/access the data • Close the file. Write a Program to perform the following operations on a text file: 1. Create file. 2. Display the original file. 3. Copy the original file to another text file (Create a duplicate copy of 4. Display the contents of duplicate file. 5. Exit def fileCreation(): ofile = open("story.txt","w+") n=int(input("Enter number of lines : ")) for i in range(n): line = input("enter sentence :") ofile.write(line) ofile.write('\n') ofile.close() the text file.) def fileCopy(): ifile = open("story.txt","r") ofile = open("newstory.txt","w") l = ifile.readlines() print (l) for i in l: ofile.write(i) ifile.close() ofile.close() def fileDisplaying1(): for l in open("story.txt","r").readlines(): print (l,end='') def fileDisplaying2(): for l in open("newstory.txt","r").readlines(): print(l,end=' ') print ("\n Creating Original Text File : \n") fileCreation() print ("\n Making Copy of the Text File \n") fileCopy() print ("\n Displaying the Original File \n") fileDisplaying1() print ("\n Displaying the Copy of the Text File \n") fileDisplaying2() Output: Creating Original Text File : Enter number of lines : 2 enter sentence :Our Own High School enter sentence :Al Warqa'a, Dubai, UAE Making Copy of the Text File ['Our Own High School\n', "Al Warqa'a, Dubai, UAE\n"] Displaying the Original File Our Own High School Al Warqa'a, Dubai, UAE Displaying the Copy of the Text File Our Own High School Al Warqa'a, Dubai, UAE ' Reading from File Method Description read() or read(n) This function facilitates reading the full file in the form of string. However one can restrict the reading to a certain limit by specifying the size in this function like read(size). readline() This helps the user reading only the first line of the file or reading line until it meets an EOF character in file. Suppose EOF is met at first, then an empty string will be returned. readlines() This function reads all lines from the file into a list; starts reading from the cursor up to the end of the file and return a list of lines. Example using read() ''' Text File foo.txt: 0123456789ABCDEF Python is a great language. Yeah its great!! ''' f = open("C:/Users/yadav.s_oow/OneDrive - GEMS Education/Desktop/Python/12/File Handling/foo.txt", "r") #or #f=open(("C:\\Users\\yadav.s_oow\\OneDrive - GEMS Education\\Desktop\\Python\\12\\File Handling\\foo.txt", "r") print("\nReading the text file from the specified folder and displaying the file contents: ") print(f.read()) ''' Output: Reading the text file from the specified folder and displaying the file contents: 0123456789ABCDEF Python is a great language. Yeah its great!! ''' Example using readline() ''' Text File foo.txt: 0123456789ABCDEF Python is a great language. Yeah its great!! ''' f = open("C:/Users/yadav.s_oow/OneDrive - GEMS Education/Desktop/Python/12/File Handling/foo.txt", "r") print("\nReading the text file from the specified folder and displaying the file contents: readline() reads one line ") print(f.readline()) ''' Output: Reading the text file from the specified folder and displaying the file contents: readline() reads one line 0123456789ABCDEF ''' Example using readlines() ''' Text File foo.txt: 0123456789ABCDEF Python is a great language. Yeah its great!! ''' f = open("C:/Users/yadav.s_oow/OneDrive - GEMS Education/Desktop/Python/12/File Handling/foo.txt", "r") print("\nReading the text file from the specified folder and displaying the file contents: readlines() reads all lines ") print(f.readlines()) ''' Output: Reading the text file from the specified folder and displaying the file contents: readlines() reads all lines ['0123456789ABCDEF\n', 'Python is a great language.\n', 'Yeah its great!!\n'] ''' Example: read(), seek() & tell() fo = open("foo.txt", "r+") str = fo.read(10) print ("Read String is : ", str) print ("Length = ",len(str)) # Check current position position = fo.tell() print ("Current file position : ", position) # Reposition pointer at the beginning once again position = fo.seek(0, 0) str = fo.read(63) print ("Again read String is : ", str) # Close opened file fo.close() ''' Text File foo.txt: 0123456789ABCDEF Python is a great language. Yeah its great!! ''' ''' Output: Read String is : 0123456789 Length = 10 Current file position : 10 Again read String is : 0123456789ABCDEF Python is a great language. Yeah its great!! ''' Q: Find output: ''' Text File foo.txt: 0123456789ABCDEF Python is a great language. Yeah its great!! ''' f = open('foo.txt', 'r') last_pos = f.tell() # get to know the current position in the file print("Last position = ",last_pos) last_pos = last_pos + 10 f.seek(last_pos) # to change the current position in a file text= f.readlines(last_pos) print (text) ''' Output: Last position = 0 ['ABCDEF\n', 'Python is a great language.\n'] ''' Q: Find output: ''' Text File foo.txt: 0123456789ABCDEF Python is a great language. Yeah its great!! ''' f = open('foo.txt', 'r') last_pos = f.tell() # get to know the current position in the file print("Last position = ",last_pos) last_pos = last_pos + 10 f.seek(last_pos) # to change the current position in a file text= f.readlines(last_pos+25) # It reads from current position to the end of line print (text) Output: Last position = 0 ['ABCDEF\n', 'Python is a great language.\n', 'Yeah its great!!\n'] Q: Find output: ''' Text File foo.txt: 0123456789ABCDEF Python is a great language. Yeah its great!! ''' f = open('foo.txt', 'r') last_pos = f.tell() # get to know the current position in the file print("Last position = ",last_pos) last_pos = last_pos + 10 f.seek(last_pos) # to change the current position in a file text= f.readlines(last_pos+10) # It reads from current position to the #end of line print (text) Output: Last position = 0 ['ABCDEF\n', 'Python is a great language.\n'] Q: Find output: ''' Text File foo.txt: 0123456789ABCDEF Python is a great language. Yeah its great!! ''' f = open('foo.txt', 'r') last_pos = f.tell() # get to know the current position in the file text= f.readlines(5) # It reads from current position to the end of line print (text) Output: ['0123456789ABCDEF\n'] Q: Find output: fo = open("foo.txt", "r+") str1 = fo.read(5) print("Str=",str1) fo.seek(8) str2=fo.read(5) print("Str=",str2) fo.seek(18,0) loc=fo.tell() print("Loc=",loc) str3=fo.read() print("Str3=",str3) ''' Text File foo.txt: 0123456789ABCDEF Python is a great language. Yeah its great!! ''' Str= 01234 Str= 89ABC Loc= 18 Str3= Python is a great language. Yeah its great!! Output: Str= 01234 Str= 89ABC Loc= 18 Str3= Python is a great language. Yeah its great!! ''' Text File foo.txt: 0123456789ABCDEF Python is a great language. Yeah its great!! ''' tell() and seek() functions in Python Files tell() f.tell() returns an integer giving the file object’s current position in the file represented as number of bytes from the beginning of the file when in binary mode and an opaque number when in text mode. seek() To change the file object’s position, use f.seek(offset, whence). The position is computed from adding offset to a reference point; the reference point is selected by the whence argument. A whence value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. whence can be omitted and defaults to 0, using the beginning of the file as the reference point Example 1 >>> >>> >>> >>> # test.txt contents: # ABCDE f = open('C:/test.txt', 'r') f.seek(3) >>> f.read() # starts reading from the 3rd character 'DE' Example 2 >>> f = open('C:/test.txt', 'r') >>> f.seek(2) # move two characters ahead >>> f.seek(2, 1) # move two characters ahead from the current position >>> f.read() 'E' io.UnsupportedOperation: can't do nonzero cur-relative seeks Example 3 >>> f = open('C:/test.txt', 'r') >>> f.seek(-3, 2) # move to the 3rd character from the end of the file io.UnsupportedOperation: can't do nonzero end-relative seeks >>> f.read() 'CDE' # Program to : # 1. Create Text File # 2. Display the text file # 3. Count two alphabets given by the user # 4. Exit def create(): ofile = open("story.txt","w+") choice = True def display(): fo = open("story.txt", "r") print ("\n Displaying the file contents using readlines() ") lines = fo.readlines() while True: line = input("enter sentence :") ofile.write(line) ofile.write('\n') choice = input("want to enter more data in file Y / N") if choice.upper() == 'N' : break ofile.close() print (lines) print ( type(lines)) fo.close() for l in lines: print (l) def count_alphabets(): # Using readlines() function fo = open("story.txt", "r") print ("\n Displaying text file ") lines = fo.readlines() alpha1=input("Enter first alphabet to be counted : ") alpha2=input("Enter second alphabet to be counted : ") fo.close() count1=0 count2=0 for l in lines: for w in l.split(): for c in w: if c.upper()==alpha1.upper(): count1=count1+1 if c.upper()==alpha2.upper(): count2=count2+1 print (alpha1," is repeated ",count1," times") print (alpha2," is repeated ",count2," times") def count_alphabets(): # using read() function f=open("story.txt", "r") print ("\n Displaying text file ") lines=f.read() print(lines) alpha1=input("Enter first alphabet to be counted : ") alpha2=input("Enter second alphabet to be counted : ") f.close() count1=0 count2=0 for c in lines: if c.upper()==alpha1.upper(): count1=count1+1 if c.upper()==alpha2.upper(): count2=count2+1 print (alpha1," is repeated ",count1," times") print (alpha2," is repeated ",count2," times") def main(): while True: print ("\n\n\n") print ("==========================================") print (" MAIN MENU ") print ("==========================================") print ("1. Create Text File ") print ("2. Display the file ") print ("3. Count two alphabets given by the user") print ("4. Exit ") ch = int(input('Enter your choice :')) if ch==1: print ("Creating the text file ") create() elif ch==2: print ("Displaying the file ") display() elif ch==3: print ("Counting two alphabets in the file : ") count_alphabets() elif ch==4: exit() else: print (' Wrong choice entered') main() Output: ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Count two alphabets given by the user 4. Exit Enter your choice :1 Creating the text file enter sentence :Our Own High School want to enter more data in file Y / NY enter sentence :Indian High School want to enter more data in file Y / NY enter sentence :Delhi Private School want to enter more data in file Y / NN ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Count two alphabets given by the user 4. Exit Enter your choice :2 Displaying the file Displaying the text file contents using readlines() ['Our Own High School\n', 'Indian High School\n', 'Delhi Private School\n'] <class 'list'> Our Own High School Indian High School Delhi Private School ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Count two alphabets given by the user 4. Exit Enter your choice :3 Counting two alphabets in the file : Displaying each character of the the text file in separate lines Enter first alphabet to be counted : H Enter second alphabet to be counted : S H is repeated 8 times S is repeated 3 times # Program to count the number of lines staring with 'A' # 1. Create Text File # 2. Display the text file # 3. Count the number of lines not starting with 'A' # 4. Exit def create(): ofile = open("story.txt","w+") choice = True while True: line = input("enter sentence :") ofile.write(line) ofile.write('\n') choice = input("want to enter more data in file Y / N") if choice.upper() == 'N' : break ofile.close() def display(): fo = open("story.txt", "r") print ("\n Displaying the text file contents using read() ") str=fo.read() print(str) fo.close() def display_count_lines_not_starting_with_A(): fin = open("story.txt", "r") print ("\n Displaying the text file contents using readlines() ") lines = fin.readlines() print ("Lines= ",lines) print ("Type of Lines : ",type(lines)) print ("Size=",len(lines)) fin.close() count=0 print ("Len \t Text ") for l in lines: print (len(l)-1,"\t",l) if l[0]!="A": count=count+1 print ("The number of lines not starting with A = ",count) def main(): while True: print ("\n\n\n") print ("==========================================") print (" MAIN MENU ") print ("==========================================") print ("1. Create Text File ") print ("2. Display the file ") print ("3. Count the number of lines not starting with 'A'") print ("4. Exit ") ch = int(input('Enter your choice :')) if ch==1: print ("Creating the text file ") create() elif ch==2: print ("Displaying the file ") display() elif ch==3: print ("Count the number of lines not starting with 'A': ") display_count_lines_not_starting_with_A() elif ch==4: exit() else: print (' Wrong choice entered') main() Output ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Count the number of lines not starting with 'A' 4. Exit Enter your choice :1 Creating the text file enter sentence :An outstanding Performance want to enter more data in file Y / NY enter sentence :Today is Monday want to enter more data in file Y / NY enter sentence :Arabic is easy language want to enter more data in file Y / NN ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Count the number of lines not starting with 'A' 4. Exit Enter your choice :2 Displaying the file Displaying the text file contents using readlines() An outstanding Performance Today is Monday Arabic is easy language Enter your choice :3 Count the number of lines not starting with 'A': Displaying the text file contents using readlines() Lines= ['An outstanding Performance\n', 'Today is Monday\n', 'Arabic is easy language\n'] Type of Lines : <class 'list'> Size= 3 Len Text 26 15 23 An outstanding Performance Today is Monday Arabic is easy language The number of lines not starting with A = 1 Q.: Write a function CharCount() in Python, which should read each character of a text file GENERATION.TXT, should count and display the occurrence of characters other than alphabets and digits. Example: If the file content is as follows: The period of first generation computers is 1946-1959. The period of second generation computers is 1959-1965. The CharCount() function should display the output as: Count = 18 Q.: Write a function CharCount() in Python, which should read each character of a text file GENERATION.TXT, should count and display the occurrence of characters other than alphabets and digits. import os def CharCount(): count=0 if os.path.isfile("GENERATION.TXT"): with open("GENERATION.TXT", "r") as f1: #print(type(f1)) for line in f1: print(line) for char in line: if not char.isalnum() and char!='\n': count+=1 print("Count = ", count) CharCount() def CharCount(): f=open("GENERATION.TXT", "r") count=0 lines=f.read() print(lines) for c in lines: if not c.isalnum() and c !='\n': count=count+1 print("count=",count) CharCount() Output: The period of first generation computers is 1946-1959. The period of second generation computers is 1959-1965. count= 18 # Counting charachters other than alphabets and digits (Text File foo.txt) import os def CharCount(): count=0 if os.path.isfile("foo.txt"): with open("foo.txt", "r") as f1: #print(type(f1)) for line in f1: print(line) for char in line: if not char.isalnum() and char!='\n': count+=1 print("Count = ", count) CharCount() 0123456789ABCDEF Python is a great language. Yeah its great!! # f=open("C:\Users\yadav.s_oow\OneDrive - GEMS # Education\Desktop\foo.txt",'r') OUTPUT: 0123456789ABCDEF Python is a great language. Yeah its great!! Count = 9 Creating Text File Using writelines() def create_file(): outFile=open('diary.txt',"w") List=["School Diary\n","Home Work\n","Time Table\n","Assignments\n"] outFile.writelines(List) print("List of lines written to the text file successfully") outFile.close() create_file() print('Reading Text File: First Method') def read_file1(): inFile = open('diary.txt', "r") str=inFile.read() print(str) read_file1() Output: List of lines written to the text file successfully Reading Text File: First Method School Diary Home Work Time Table Assignments Using writelines and readline() function def create_file1(): outFile=open('daynote.txt',"w") List=["Mathematics\n","Physics\n","Computer Science\n"] outFile.writelines(List) print("List of lines written to the textfile successfully") outFile.close() print() create_file1() print('Reading Text File: using readline() Method') def read_file(): inFile = open('daynote.txt', "r") str=True # or str=" " while str: str=inFile.readline() print(str) inFile.close() read_file() Output: List of lines written to the textfile successfully Reading Text File: using readline() Method Mathematics Physics Computer Science Q: Write a menu driven programs to perform the following operations on a text file. i. Write a functions to create a text file DATA1.TXT ii. Display the file contents and perform the following operation. iii. Read data from a text file 'DATA1.TXT', and display word which have maximum number of vowels characters. iv. Write a function to count the number of lines in a text file, ‘DATA1.TXT’ which starts and end with ‘T’ and ‘e’ respectively. v. Exit Relative and absolute path Absolute path C:\Python\calc.txt Non absolute path (Relative path) calc.txt 1. Write a menu driven programs to perform the following operations on a text file. 7 (i) Write a function create a text file “POEM.TXT”. (ii) Write a function to display text file. (iii) Write another function WCount() in python to count the number of words present in the text file “POEM.TXT”. If the file contains: I have a tree, a Green, green tree To shade me from the sun. Output of the function should be: Count of words:14 (iv) Write a function to count two characters A and E in the text file. Count of A/a: 4 Count of E/e: 12 (v)Exit Write a menu driven programs to perform the following operations on a binary file "TEACHER.DAT" has structure (NO, NAME, DEPARTMNT, SALARY, GENDER). (i) Write a function CREATE_REC() to input data and add to file "TEACHER.DAT". (ii) Write a function SEARCH_ REC(NAME) to search record by passing teacher’s name as function argument and print searched result. (iii) Display file contents. (iv) Exit Write a menu driven programs to perform the following operations on a binary file "STORE.DAT" has structure (ITEM_ID, ITEM_NAME, QTY,PRICE). 1. Write a function CREATE_REC() to input data and add to file "STORE.DAT". 2. Write a function Display_ Rec() in python to display the details of items have quantity is more than 35 from the file "STORE.DAT" and also print the total number of records in the file. 3. Display file contents. 4. Exit Write a menu driven programs to perform the following operations on a binary file “emp.dat” has structure [EID, Ename, designation, salary]. I. (Write a user defined function CreateEmp () to input data for a record and create a file emp.dat. II. Write a function display () in Python to display the detail of all employees, whose salary is more than 30000. III. Display the file contents IV. Exit Write a menu driven programs to perform the following operations on a binary file “emp.DAT” has structure (EID, Ename, designation, salary). i. Write a function to add more records of employees in existing file emp.dat. ii. Write a function Show_Salesmen in Python that would read detail of employee from file “emp.dat” and display the details of those employee whose designation is “Salesman”. iii. Display File contents. iv. Exit Q2 Write a menu driven programs to perform the following operations on a binary file "ATTENDANCE.DAT" has structure [Admission_Number, Name, Attendance, Working_days] . i. Write a user defined function Add_Student() in Python to input data for a Student and add it to a binary file "ATTENDANCE.DAT" ii. Write a function count_short_attendance() in Python that would read contents of the file "ATTENDANCE.DAT" and display the details of those students whose attendance is below 75%, also display the total number of students with attendance below 75%. iii. Display file contents. iv. Exit Q1. Write a menu driven programs to perform the following operations on a binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]. i. Write a user defined function CreateFile() to input data for a record and add to “Book.dat” . ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter and count return number of books by the given Author are stored in the binary file “Book.dat”. Also display the book details written by the same Author iii. Display File contents. iv. Exit An alternate code is given without using try-except, to read from a binary data file BOOK.DAT containing records as [BNo, Name, Author, Price] CBSE Board 2015 OD : Q. No. 4: Based on File Handling (a) Differentiate between the following: (1 mark) (i) f = open ('diary. txt', 'a') (ii) f = open ('diary. txt', 'w') (b) Write a method in python to read the content from a text file Story.txt line by line and display the same on screen. (2 marks) (c) Consider the following definition of class Student. Write a method in python to write the content in a pickled file student.dat having Admno and Name of the students. (3 marks) 4 (a) Differentiate between the following: (i) f = open ('diary. txt', 'a') (ii) f = open ('diary. txt', 'w') Ans.: (i) diary.txt is opened for appending data (ii) diary.txt is opened for writing data 4 (b) Write a method in python to read the content from a text file Story.txt line by line and display the same on screen. Ans.: def create_file(): outFile=open("story.txt","w") List=["Computer Science\n","Physics\n","Mathematics\n","Chemistry\n"] outFile.writelines(List) print("List of lines written to the text file successfully") outFile.close() create_file() OR def read_file2(): print('Reading Text File: First Method') inFile = open("story.txt", "r") def read_file(): print ("\n Displaying the text file: ") inFile = open("story.txt", "r") lines = inFile.readlines() str=inFile.read() inFile.close() print(str) for l in lines: print (l) inFile.close() read_file2() read_file() CBSE 2015 D: Q No. 4 File Handling (a) Differentiate between the following: (1 mark) (i) f = open ('diary. txt', 'r') (ii) f = open ('diary. txt', 'w') (b) Write a method in python to read the content from a text file diary.txt line by line and display the same on screen. (2 marks) (c) Consider the following definition of class Member, write a method in python to write the content in a pickled file member.dat having MemNo and Member name (3 marks) 4 (a) Differentiate between the following: (i) f = open ('diary. txt', 'r') (ii) f = open ('diary. txt', 'w') Ans.: (i) diary.txt is opened for reading data (ii) diary.txt is opened for writing data ( 1 mark for writing correct difference) OR (½ Mark for each correct explanation of (i) and (ii)) 4. (b) Write a method in python to read the content from a text file diary.txt line by line and display the same on screen. (2 marks) Ans.: def create_file(): outFile=open('diary.txt',"w") List=["School Diary\n","Home Work\n","Time Table\n","Assignments\n"] outFile.writelines(List) print("List of lines written to the textfile successfully") outFile.close() create_file() print('Reading Text File: First Method') def read_file1(): inFile = open('diary.txt', "r") str=inFile.read() print(str) read_file1() OR print('Reading Text File: 2nd Method') def read_file2(): inFile = open('diary.txt', "r") for line in inFile: print (line) read_file2() (½ Mark for opening the file) (1 Mark for reading all lines) (½ Mark for displaying all lines) OR def read_file2(): inFile = open('diary.txt', "r") print ("\n Displaying the text file: ") lines = inFile.readlines() inFile.close() for l in lines: print (l) read_file2() CBSE 2016 D: Q No. File Handling 4 (a) Write a statement in Python to perform the following operations: ● To open a text file "MYPET.TXT", in write mode ● To open a text file "MYPET.TXT", in read mode 4(b) Write a method in python to write multiple line of text contents into a text file daynote.txt line. 4(c) Consider the following definition of class Employee, write a method in python to search and display the content in a pickled file emp.dat (which has Empno and Ename of employees ),where Empno is matching with ‘A0005’. 4 (a) Write a statement in Python to perform the following operations: ● To open a text file "MYPET.TXT", in write mode ● To open a text file "MYPET.TXT", in read mode Ans. : • f1 = open("MYPET.TXT", "w") • f2 = open("MYPET.TXT", "r") ( ½ Mark for each correct statement) 4(b) Write a method in python to write multiple line of text contents into a text file daynote.txt line. Ans.: def create_file1(): outFile=open('daynote.txt',"w") List=["School Diary\n","Home Work\n","Time Table\n", "Assignments\n"] outFile.writelines(List) print("List of lines written to the textfile successfully") outFile.close() print() create_file1() OR def create_file2(): f = open('daynote.txt',"w") while True: line = input("Enter line: ") f.write(line) f.write('\n') choice = input("Are there more lines : ") if choice=='N': Note: Using writelines() is also correct break (½ Mark for opening file in appropriate mode) f.close() (½ Mark for end of file check and loop) print() (½ Mark for taking input from user) create_file2() (½ Mark for writing the line into the file) print('Reading Text File: First Method') def read_file1(): inFile = open('daynote.txt', "r") str=inFile.read() print(str) read_file1() print() OR print('Reading Text File: 2nd Method') def read_file2(): inFile = open('daynote.txt', "r") for line in inFile: print (line) read_file2() CBSE 2017 OD: Q No. 4 File Handling 4 (a) Differentiate between file modes r+ and rb+ with respect to Python. (1 mark) 4 (b) Write a method in python to read lines from a text file MYNOTES.TXT, and display those lines, which are starting with an alphabet ‘K’. (2 marks) 4 (c) Considering the following definition of class FACTORY, write a method in Python to search and display the content in a pickled file FACTORY.DAT,(having FCTID Factory ID, FCTNM Factory Name and PROD Production) where FCTID is matching with the value ‘105’. (3 marks) Ans.: 4 (a) r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. (1 mark for correct difference ) OR (½ Mark for each correct use of r+ and rb+) 4 (b) def display(): file=open('MYNOTES.TXT','r') line=file.readline() while line: if line[0]=='K' : print (line) line=file.readline() file.close() (½ Mark for opening the file) (½ Mark for reading all lines) (½ Mark for checking condition for line starting with K) (½ Mark for displaying line) # Program to count the number of uppercase and lowercase characters in the text file # 1. Create Text File # 2. Display the text file and # 3. count the number of uppercase and lowercase characters in the text file # 4. Exit def create(): ofile = open("story.txt","w+") choice = True while True: line = input("enter sentence :") ofile.write(line) ofile.write('\n') choice = input("want to enter more data in file Y / N") if choice.upper() == 'N' : break ofile.close() def display(): fo = open("story.txt", "r") print ("\n Displaying the text file contents using read() ") str=fo.read() print(str) fo.close() def display_count_upper_lower_case(): fo = open("story.txt", "r") print ("\n Displaying the text file contents using read() ") str=fo.read() print(str) fo.close() caps=0 small=0 for ch in str: if ch.isupper(): caps=caps+1 if ch.islower(): small=small+1 print ("The number of uppercase characters = ",caps) print ("The number of lowercase characters = ",small) def main(): while True: print ("\n\n\n") print ("==========================================") print (" MAIN MENU ") print ("==========================================") print ("1. Create Text File ") print ("2. Display the file ") print ("3. Counting Uppercase and Lowercase alphabets") print ("4. Exit ") ch = int(input('Enter your choice :')) if ch==1: print ("Creating the text file ") create() elif ch==2: print( "Displaying the file ") display() elif ch==3: print ("Counting Uppercase and Lowercase alphabets ") display_count_upper_lower_case() elif ch==4: exit() else: print(' Wrong choice entered') main() Output ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Counting Uppercase and Lowercase alphabets 4. Exit Enter your choice :1 Creating the text file enter sentence :Our Own want to enter more data in file Y / NY enter sentence :High School want to enter more data in file Y / NN ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Counting Uppercase and Lowercase alphabets 4. Exit Enter your choice :2 Displaying the file Displaying the text file contents using read() Our Own High School ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Counting Uppercase and Lowercase alphabets 4. Exit Enter your choice :3 Counting Uppercase and Lowercase alphabets Displaying the text file contents using read() Our Own High School The number of uppercase characters = 4 The number of lowercase characters = 12 # Program to : # 1. Create Text File # 2. Display the text file # 3. Count Two Words given by the user # 4. Exit def create(): ofile = open("story.txt","w+") choice = True while True: line = input("enter sentence :") ofile.write(line) ofile.write('\n') choice = input("want to enter more data in file Y / N") if choice.upper() == 'N' : break ofile.close() def display(): fo = open("story.txt", "r") print ("\n Displaying the text file contents using read() ") str=fo.read() print(str) fo.close() def count_word(): fo = open("story.txt", "r") print ("\n Displaying each character of the the text file in separate lines ") lines = fo.readlines() word1=input("Enter first word to be counted : ") word2=input("Enter second word to be counted : ") fo.close() count1=0 count2=0 for Line in lines: for w in Line.split(): if w.upper()==word1.upper(): count1=count1+1 if w.upper()==word2.upper(): count2=count2+1 print (word1," is repeated ",count1," times") print (word2," is repeated ",count2," times") def main(): while True: print ("\n\n\n") print ("==========================================") print (" MAIN MENU ") print ("==========================================") print ("1. Create Text File ") print ("2. Display the file ") print ("3. Counting two words given by the user ") print ("4. Exit ") ch = int(input('Enter your choice :')) if ch==1: print ("Creating the text file ") create() elif ch==2: print ("Displaying the file ") display() elif ch==3: print ("Counting two words in the file : ") count_word() elif ch==4: exit() else: print (' Wrong choice entered') main() Output: ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Counting two words given by the user 4. Exit Enter your choice :1 Creating the text file enter sentence :Our Own High School want to enter more data in file Y / NY enter sentence :Delhi Private High School want to enter more data in file Y / NN ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Counting two words given by the user 4. Exit Enter your choice :2 Displaying the file Displaying the text file contents using readlines() ['Our Own High School\n', 'Delhi Private High School\n'] Our Own High School Delhi Private High School ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Counting two words given by the user 4. Exit Enter your choice :3 Counting two words in the file : Displaying each character of the the text file in separate lines Enter first word to be counted : High Enter second word to be counted : Delhi High is repeated 2 times Delhi is repeated 1 times # Program to display text file in reverse , display each word in separate line and display each character in separate lines. # 1. Create Text File # 2. Display the text file # 3. Read and display file Backwards # 4. Display each character in separate line # 5. Display each word in separate line # 5. Exit def create(): ofile = open("story.txt","w+") choice = True while True: line = input("enter sentence :") ofile.write(line) ofile.write('\n') choice = input("want to enter more data in file Y / N") if choice.upper() == 'N' : break ofile.close() def display(): fo = open("story.txt", "r") print ("\n Displaying the text file contents using read() ") str=fo.read() print(str) fo.close() def display_each_word_in_separate_lines(): fo = open("story.txt", "r") print ("\n Displaying each word of the text file in separate lines ") lines = fo.readlines() fo.close() words=0 for Line in lines: for w in Line.split(): print (w) words=words+1 print ("Number of words = ",words) def display_each_char_in_separate_lines(): fo = open("story.txt", "r") print ("\n Displaying each character of the the text file in separate lines ") lines = fo.readlines() fo.close() for Line in lines: for w in Line.split(): for ch in w: print (ch) def read_display_file_backwards(): fo = open("story.txt", "r") print ("\n Displaying the text file contents backwards ") lines = fo.readlines() print ("Lines : ", lines) size=len(lines) print ("Number of lines =",size) fo.close() for i in range(size-1,-1,-1): print (lines[i][::-1]) def main(): while True: print ("\n\n\n") print ("==========================================") print (" MAIN MENU ") print ("==========================================") print ("1. Create Text File ") print ("2. Display the file ") print ("3. Read and display file Backwards ") print ("4. Display each character in separate line ") print ("5. Display each word in separate line ") print ("6. Exit ") ch = int(input('Enter your choice :')) if ch==1: print ("Creating the text file ") create() elif ch==2: print ("Displaying the file ") display() elif ch==3: read_display_file_backwards() elif ch==4: display_each_char_in_separate_lines() elif ch==5: display_each_word_in_separate_lines() elif ch==6: exit() else: print (' Wrong choice entered') main() Output: ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Read and display file Backwards 4. Display each character in separate line 5. Display each word in separate line 6. Exit Enter your choice :1 Creating the text file enter sentence :Our Own want to enter more data in file Y / NY enter sentence :High School want to enter more data in file Y / NN ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Read and display file Backwards 4. Display each character in separate line 5. Display each word in separate line 6. Exit Enter your choice :2 Displaying the file Displaying the text file contents using readlines() ['Our Own\n', 'High School\n'] Our Own High School ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Read and display file Backwards 4. Display each character in separate line 5. Display each word in separate line 6. Exit Enter your choice :3 Displaying the text file contents backwards Lines : ['Our Own\n', 'High School\n'] Number of lines = 2 loohcS hgiH nwO ruO ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Read and display file Backwards 4. Display each character in separate line 5. Display each word in separate line 6. Exit Enter your choice :5 Displaying each word of the the text file in separate lines Our Own High School Number of words = 4 ========================================== MAIN MENU ========================================== 1. Create Text File 2. Display the file 3. Read and display file Backwards 4. Display each character in separate line 5. Display each word in separate line 6. Exit Enter your choice :4 Displaying each character of the text file in separate lines O u r O w n H i g h S c h o o l CSV (Comma Separated Values File) # Write a program to perform read and write operation with .csv file. import csv def readcsv(): with open('data.csv','rt')as f: data = csv.reader(f) #reader function to generate a reader object for row in data: print(row) def writecsv(): with open('data.csv', mode='a', newline='') as file: writer = csv.writer(file, delimiter=',', quotechar='"') #write new record in file writer.writerow(['4', 'Devansh', 'Arts', '404']) print(“Enter 1 to Read Data or Enter 2 to Write data: ") a=int(input()) if a==1: readcsv() elif a==2: writecsv() print("The write operation successful !") print("Data.csv is written in Excel file") else: print("Invalid value") Output: Press-1 to Read Data and Press-2 to Write data: 2 The write operation successful ! Data.csv is written in Excel file >>> Press-1 to Read Data and Press-2 to Write data: 2 The write operation successful ! Data.csv is written in Excel file >>> Press-1 to Read Data and Press-2 to Write data: 1 ['4', 'Devansh', 'Arts', '404'] ['4', 'Devansh', 'Arts', '404'] Write programs for following: 1. Count the number of characters from a file story.txt. (Don’t count blank spaces or ‘ \n’) 2. Check if file exists, then delete it else display message it does not exist 3. WAP to remove all the lines that contain character ‘A’ in it and write it to another file. 4. Count number of lines in a text file. 5. Count number of vowels in a text file. 6. Count the number of ‘is’ word in a text file. Program: Count the number of characters from a file story.txt. (Don’t count blank spaces or ‘ \n’) fin=open("story.txt",'r') Output: File contents are as follows: str=fin.read( ) Our Own print("File contents are as follows: ") High School print(str) The text file has : 16 characters count=0 for i in str: if i!=' ' and i!='\n': count=count+1 print("The text file has : ", count," characters. ") fin.close() Programs: Check if file exists, then delete it else display message it does not exist import os ch='' if os.path.exists("sample.txt"): print("The file exists ! ") ch=input() if ch.upper()=='Y': os.remove("sample.txt") print("The file deleted !") else: print ("File not deleted ! ") else: print("The file does not exist") Output: The file exists ! Do you want to delete (Y/N) ? N File not deleted ! >>> The file exists ! Do you want to delete (Y/N) ? Y The file deleted ! >>> The file does not exist Find Output: f = open("story.txt", "r") print("Name of the File: ", f.name) print("File-Mode : ", f.mode) print("File encoding format : ", f.encoding) print("Is File closed? ", f.closed) f.close() print("Is File closed? ", f.closed) Output: Name of the File: story.txt File-Mode : r File encoding format : cp1252 Is File closed? False Is File closed? True Windows-1252 or CP-1252 (code page 1252) is a single-byte character encoding of the Latin alphabet, used by default in the legacy components of Microsoft Windows for English and some other Western languages (other languages use different default encodings) Cp-1252 or Windows- 1252 WAP TO REMOVE ALL THE LINES THAT CONTAIN CHARACTER ‘A’ IN IT AND WRITE IT TO ANOTHER FILE. Output File( trial.txt) HELLO USER! PYTHON FILES Basic Usage of csv.writer() Example 1: Write into CSV files with csv.writer() Suppose we want to write a CSV file with the following entries: SN,Name,Contribution 1,Linus Torvalds,Linux Kernel 2,Tim Berners-Lee,World Wide Web 3,Guido van Rossum,Python Programming Output: <class '_csv.reader'> data= <_csv.reader object at 0x03DC8300> ['SN', 'Name', 'Contribution'] ['1', 'Linus Torvalds', 'Linux Kernel'] ['2', 'Tim Berners-Lee', 'World Wide Web'] ['3', 'Guido van Rossum', 'Python Programming'] Here's how we do it import csv with open('innovators.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(["SN", "Name", "Contribution"]) writer.writerow([1, "Linus Torvalds", "Linux Kernel"]) writer.writerow([2, "Tim Berners-Lee", "World Wide Web"]) writer.writerow([3, "Guido van Rossum", "Python Programming"]) def readcsv(): with open('innovators.csv','rt')as f: data = csv.reader(f) #reader function to generate a reader object print(type(data)) print("data=",data) for row in data: print(row) readcsv() Example 2: Writing Multiple Rows with writerows() If we need to write the contents of the 2-dimensional list to a CSV file, here's how we can do it. import csv row_list = [["SN", "Name", "Contribution"], [1, "Linus Torvalds", "Linux Kernel"], [2, "Tim Berners-Lee", "World Wide Web"], [3, "Guido van Rossum", "Python Programming"]] with open('protagonist.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerows(row_list) def readcsv(): with open('protagonist.csv','rt')as f: data = csv.reader(f) #reader function to generate a reader object print(type(data)) print("data=",data) for row in data: print(row) Output: readcsv() <class '_csv.reader'> data= <_csv.reader object at 0x03168370> ['SN', 'Name', 'Contribution'] ['1', 'Linus Torvalds', 'Linux Kernel'] ['2', 'Tim Berners-Lee', 'World Wide Web'] ['3', 'Guido van Rossum', 'Python Programming'] CSV Files with Custom Delimiters By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. Few popular ones are | and \t. Suppose we want to use | as a delimiter in the innovators.csv file of Example 1. To write this file, we can pass an additional delimiter parameter to the csv.writer() function. Let's take an example. Example 3: Write CSV File Having Pipe Delimiter import csv data_list = [["SN", "Name", "Contribution"], [1, "Linus Torvalds", "Linux Kernel"], [2, "Tim Berners-Lee", "World Wide Web"], [3, "Guido van Rossum", "Python Programming"]] with open('innovators.csv', 'w', newline='') as file: writer = csv.writer(file, delimiter='|') writer.writerows(data_list) def readcsv(): with open('innovators.csv','rt')as f: data = csv.reader(f) #reader function to generate a reader object for row in data: print(row) readcsv() Output: ['SN|Name|Contribution'] ['1|Linus Torvalds|Linux Kernel'] ['2|Tim Berners-Lee|World Wide Web'] ['3|Guido van Rossum|Python Programming'] CSV files with Quotes Some CSV files have quotes around each or some of the entries. Let's take quotes.csv as an example, with the following entries: "SN";"Name";"Quotes" 1;"Buddha";"What we think we become" 2;"Mark Twain";"Never regret anything that made you smile" 3;"Oscar Wilde";"Be yourself everyone else is already taken" Using csv.writer() by default will not add these quotes to the entries. In order to add them, we will have to use another optional parameter called quoting. Let's take an example of how quoting can be used around the non-numeric values and ; as delimiters. Example 4: Write CSV files with quotes import csv row_list = [ ["SN", "Name", "Quotes"], [1, "Buddha", "What we think we become"], [2, "Mark Twain", "Never regret anything that made you smile"], [3, "Oscar Wilde", "Be yourself everyone else is already taken"] ] with open('quotes.csv', 'w', newline='') as file: writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';') writer.writerows(row_list) csv.QUOTE_NONNUMERIC Instructs writer objects to quote all non-numeric fields. def readcsv(): with open('quotes.csv','rt')as f: data = csv.reader(f) #reader function to generate a reader object Output: for row in data: ['SN;"Name";"Quotes"'] print(row) ['1;"Buddha";"What we think we become"'] readcsv() ['2;"Mark Twain";"Never regret anything that made you smile"'] ['3;"Oscar Wilde";"Be yourself everyone else is already taken"'] CSV files with custom quoting character We can also write CSV files with custom quoting characters. For that, we will have to use an optional parameter called quotechar. Let's take an example of writing quotes.csv file in Example 4, but with * as the quoting character. Example 5: Writing CSV files with custom quoting character import csv row_list = [ ["SN", "Name", "Quotes"], [1, "Buddha", "What we think we become"], [2, "Mark Twain", "Never regret anything that made you smile"], [3, "Oscar Wilde", "Be yourself everyone else is already taken"] ] with open('quotes.csv', 'w', newline='') as file: writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';', quotechar='*') writer.writerows(row_list) def readcsv(): with open('quotes.csv','rt')as f: data = csv.reader(f) #reader function to generate a reader object for row in data: print(row) readcsv() Output: ['*SN*;*Name*;*Quotes*'] ['1;*Buddha*;*What we think we become*'] ['2;*Mark Twain*;*Never regret anything that made you smile*'] ['3;*Oscar Wilde*;*Be yourself everyone else is already taken*'] CBSE 2017 Compartment 4. (a) Differentiate between file modes r+ and r with respect to Python. 1 (b) Write a method in Python to read lines from a text file NOTES.TXT, and count those lines, which are ending with ‘.’ or ‘,’. 2 (c) Considering the following definition of class FURNITURE, write a method in Python to search and display the content in a pickled file COMPANY.DAT, where FTYPE is matching with the value ‘HOME’. class FURNITURE: def_init_(self,CODE,FTYPE,PRICE): self.CODE = CODE self.FTYPE = FTYPE self.PRICE = 1000 def Display(self): print ( self.CODE,":",self.FTYPE,":",self.PRICE) 3 CBSE 2018 4 (a) Write a statement in Python to open a text file STORY.TXT so that new contents can be added at the end of it. 1 (b) Write a method in python to read lines from a text file INDIA.TXT, to find and display the 2 occurrence of the word “India”. For example: If the content of the file is _______________________________________________________________________ “India is the fastest growing economy. India is looking for more investments around the globe. The whole world is looking at India as a great market. Most of the Indians can foresee the heights that India is capable of reaching.” _______________________________________________________________________ The output should be 4 CBSE 2018 4 (c) Considering the following definition of class MULTIPLEX, write a method in python to search and display all the content in a pickled file CINEMA.DAT, where MTYPE is matching with the value ‘Comedy’. 3 class MULTIPLEX: def __init__(self,mno,mname,mtype): self.MNO = mno self.MNAME = mname self.MTYPE = mtype def Show(self): print (self.MNO:"*",self.MNAME,"$",self.MTYPE) CBSE 2018 Compartment 4. (a) Write a statement in Python to open a text file NOTES.TXT so that new contents can be written in it. 1 (b) Write a method in python to read lines from a text file INDIA.TXT, to find and display the occurrence of the word “INDIA” or “India”. 2 For example: If the content of the file is __________________________________________________________________ INDIA is a famous country all over the world. Geographically, India is located to the south of Asia continent. India is a high population country and well protected from all directions naturally. India is a famous country for its great cultural and traditional values all across the world. __________________________________________________________________ The output should be 4 CBSE 2018 Compartment 4. (c) Considering the following definition of class SHOPCOMPLEX, write a method in python to search and display all the content in a pickled file SHOP.DAT, where STYPE is matching with the value ‘Stationary’. class SHOPCOMPLEX: def __init__(self,sno,sname,stype): self.SNO = sno self.SNAME = sname self.STYPE = stype def Display(self): print (self.SNO,",",self.SNAME,"#",self.STYPE) 3 CBSE 2019 4 (a) Write a statement in Python to open a text file WRITEUP.TXT so that new content can be written in it. 1 Or (a) Write a statement in Python to open a text file README.TXT so that existing content can be read from it. 1 (b) Write a method/function ISTOUPCOUNT() in python to read contents from a text file WRITER.TXT, to count and display the occurrence of the word “IS” or “TO” or “UP”. 2 For example: If the content of the file is _______________________________________________________________________ IT IS UP TO US TO TAKE CARE OF OUR SURROUNDING. IT IS NOT POSSIBLE ONLY FOR THE GOVERNMENT TO TAKE RESPONSIBILITY _______________________________________________________________________ The method/function should display Count of IS TO and UP is 6 CBSE 2019 Or (b) Write a method/function AEDISP() in python to read lines from a text file WRITER.TXT, and display those lines, which are starting either with A or starting with E. 2 For example: If the content of the file is _______________________________________________________________________ A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH. WE SHOULD TAKE CARE OF OUR ENVIRONMENT. EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD. _______________________________________________________________________ The method should display A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH. EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD. CBSE 2019 (c) Considering the following definition of class STOCK, write a method / function COSTLY() in python to search and display Name and Price from a pickled file STOCK.DAT, where Price of the items are more than 1000. class Stock: def __init__(self,N,P): self.Name=N self.Price=P def Show(self): print (self.Name,"@",self.Price) OR 3 CBSE 2019 (c) Considering the following definition of class DOCTORS, write a method /function SPLDOCS() in python to search and display all the content from a pickled file DOCS.DAT, where Specialisation of DOCTORS is “CARDIOLOGY”. 3 class DOCTORS: def __init__(self,N,S): self.Name=N self.Specialisation=S def Disp(self): print (self.Name,"#",self.Specialisation) CBSE 2019 Compartment 4 (a) Write a statement in Python to open a text file CONTENT.TXT so that new contents can be written in it. 1 OR (a) Write a statement in Python to open a text file REMARKS.TXT so that existing content can be read from it. 1 (b) Write a method/function BIGWORDS() in Python to read contents from a text file CODE.TXT, to count and display the occurrence of those words, which are having 5 or more alphabets. 2 For example : If the content of the file is ME AND MY FRIENDS ENSURE SAFETY AND SECURITY OF EVERYONE OR CBSE 2019 Compartment (b) Write a method/function BIGLINES() in Python to read lines from a text file CONTENT.TXT, and display those lines, which are bigger than 20 characters. 2 For example : If the content of the file is Stay positive and happy Work hard and dont give up hope Be open to criticism and keep learning Surround yourself with happy, warm and genuine people The method/function should display Be open to criticism and keep learning Surround yourself with happy, warm and genuine people File Programs from NCERT Textbook ''' Let us now write a program that accepts a string from the user and writes it to a text file. Thereafter, the same program reads the text file and displays it on the screen. Program 2-1 Writing and reading to a text file ''' Output: fobject=open("testfile.txt","w") # creating a data file Enter the contents to be written in the file: sentence=input("Enter the contents to be written in the file: ") roll_numbers = [1, 2, 3, 4, 5, 6] fobject.write(sentence) # Writing data to the file Now reading the contents of the file: fobject.close() # Closing a file roll_numbers = [1, 2, 3, 4, 5, 6] print("Now reading the contents of the file: ") fobject=open("testfile.txt","r") #looping over the file object to read the file for str in fobject: print(str) fobject.close() Application of seek() and tell() Output: Learning to move the file object roll_numbers = [1, 2, 3, 4, 5, 6] Initially, the position of the file object is: 33 Now the file object is at the beginning of the file: 0 We are moving to 6th byte position from the beginning of file The position of the file object is at 5 numbers = [1, 2, 3, 4, 5, 6] Application of seek() and tell() print("Learning to move the file object") fileobject=open("testfile.txt","r+") str=fileobject.read() print(str) print("Initially, the position of the file object is: ",fileobject. tell()) fileobject.seek(0) print("Now the file object is at the beginning of the file: ",fileobject.tell()) fileobject.seek(5) print("We are moving to 6th byte position from the beginning of file") print("The position of the file object is at", fileobject.tell()) str=fileobject.read() print(str) #Program 2-3 To create a text file and write data in it # program to create a text file and add data fileobject=open("practice.txt","w+") while True: data= input("Enter data to save in the text file: ") fileobject.write(data) fileobject.write('\n') ans=input("Do you wish to enter more data?(y/n): ") if ans=='n': break fileobject.close() Output: #Program 2-4 To display data from a text file fileobject=open("practice.txt","r") str = fileobject.read() print(str) fileobject.close() Enter data to save in the text file: Our Own High School Do you wish to enter more data?(y/n): y Enter data to save in the text file: Dubai, U.A.E. Do you wish to enter more data?(y/n): n Our Own High School Dubai, U.A.E. #Program 2-5 To perform reading and writing operation in a text file fileobject=open("report.txt", "w+") print ("WRITING DATA IN THE FILE") print() # to display a blank line while True: line= input("Enter a sentence: ") fileobject.write(line) fileobject.write('\n') print("The byte position : ",fileobject.tell()) choice=input("Do you wish to enter more data? (y/n): ") if choice in ('n','N'): break print("The byte position of file object : ",fileobject.tell()) fileobject.seek(0) #places file object at beginning of file print() print("READING DATA FROM THE FILE") str=fileobject.read() print(len(str)) print(str) Output: WRITING DATA IN THE FILE Enter a sentence: Our Own The byte position : 9 Do you wish to enter more data? (y/n): y Enter a sentence: High School The byte position : 22 Do you wish to enter more data? (y/n): y Enter a sentence: Dubai The byte position : 29 Do you wish to enter more data? (y/n): n The byte position of file object : 29 READING DATA FROM THE FILE 26 Our Own High School Dubai #Program 2-6 Pickling data in Python import pickle listvalues=[1,"Geetika",'F', 26] fileobject=open("mybinary.dat", "wb") pickle.dump(listvalues,fileobject) fileobject.close() #Program 2-7 Un-pickling data in Python import pickle print("The data that were stored in file are: ") fileobject=open("mybinary.dat","rb") objectvar=pickle.load(fileobject) fileobject.close() print(objectvar) Output: The data that were stored in file are: [1, 'Geetika', 'F', 26] 4 (c) Consider the following definition of class Student. Write a method in python to write the content in a pickled file student.dat class Student: def __init__(self,A,N): self.Admno=A self.Name=N def Show(self): print self. Admno , "\t#\t" , self.Name Ans.: import pickle class Student: def __init__(self, A,N): self. Admno=A self.Name=N def Show(self): print (self. Admno, "\t#\t" , self.Name) def enter_data(self): self. Admno =input("Enter Admission number : ") self.Name=input("Enter member name : ") def Store_Data(): f=open("student.dat","wb") n=int(input("Enter the no. of Students:")) s= Student(0,"") for i in range(n): s.enter_data() pickle.dump(s,f) f.close() def display(): print ('Adm No\t\tName') s= Student(0,"") f=open("student.dat","rb") try: while True: s= pickle.load(f) s.Show() except EOFError: f.close() s=Student(0,"") Store_Data() display() Output: Enter the no. of Students:2 Enter Admission number : 11 Enter member name : abc Enter Admission number : 22 Enter member name : xyz Adm No Name 11 # abc 22 # xyz 4 (c) Consider the following definition of class Member, write a method in python to write the content in a pickled file member.dat (3 marks) class Member: def __init__(self): self.Memno=0 self.Name="" def Show(self): print self.Memno, "\t#\t" , self.Name Ans. : import pickle class Member: def __init__(self, A,N): self.Memno=A self.Name=N def Show(self): print (self.Memno, "\t#\t" , self.Name) def enter_data(self): self.Memno =input("Enter member number : ") self.Name=input("Enter member name : ") def Store_Data(): f=open("Member.dat","wb") n=int(input("Enter the no. of Members:")) s= Member(0,"") for i in range(n): s.enter_data() pickle.dump(s,f) f.close() def display(): print (‘M No\t\tName') s= Member(0,"") f=open("Member.dat","rb") try: while True: s= pickle.load(f) s.Show() except EOFError: f.close() s=Member(0,"") Store_Data() display() Output: Enter the no. of Members:2 Enter member number : 123 Enter member name : Sachin Enter member number : 345 Enter member name : Rohit M No Name 123 # Sachin 345 # Rohit 4(c) Consider the following definition of class Employee, write a method in python to search and display the content in a pickled file emp.dat, where Empno is matching with ‘A0005’. class Employee: def __init__(self, A,N): self.Empno="" self.EName=N def Show(self): print (self.Empno, "\t#\t" , self.EName) def enter_data(self): self.Empno =input("Enter Admission number : ") self.EName=input("Enter Employee EName : ") Ans.: import pickle class Employee: def __init__(self, A,N): self.Empno="" self.EName=N def Show(self): print (self.Empno, "\t#\t" , self.EName) def enter_data(self): self.Empno =input("Enter Admission number : ") self.EName=input("Enter Employee EName : ") def Store_Data(): f=open("Employee.dat","wb") n=int(input("Enter the no. of Employees:")) s= Employee(0,"") for i in range(n): s.enter_data() pickle.dump(s,f) f.close() def display(): print ('Adm No\t\tEName') s= Employee(0,"") f=open("Employee.dat","rb") try: while True: s= pickle.load(f) s.Show() except EOFError: f.close() def search(): f=open("Employee.dat","rb") try: while True: e = pickle.load(f) if e.Empno == 'A0005': e.Show() except EOFError: pass f.close() s=Employee("","") Store_Data() display() search() (½ Mark for correct function header) (½ Mark for opening the file emp.dat correctly) (½ Mark for correct file check and loop) (½ Mark for correct load()) (½ Mark for correct checking of Empno) (½ Mark for displaying the record) 4 (c) import pickle def ques4c( ): f=Factory(0,’’ ) file=open('FACTORY.DAT','rb') try: while True: f=pickle.load(file) if f.FCTID==105: f.Display() except EOFError: pass file.close() (½ Mark for correct method header) (½ Mark for opening the file FACTORY.DAT correctly) (½ Mark for correct loop) (½ Mark for correct load( )) (½ Mark for correct checking of FCTID) (½ Mark for displaying the record) Create a Quantity Item with name and Quantity as data members. write a menu driven pgm to create a file Item.dat to store Items details in the ascending order of name and do the following : 1)append record 2)insert new record 3)delete a record 4)modify the record 5)display all the details 6)search record import pickle import os class Item: def __init__(self): self.Ino=0 self.name="" self.Quantity=0.0 self.Rate=0.0 self.Amount=0.0 def storedata(self): self.Ino=int(input("Enter Item Number : ")) self.name=input ('Enter name: ') self.Quantity= float(input('Enter Quantity: ')) self.Rate=float(input("Enter Rate : ")) self.Amount=float(input("Enter Amount : ")) def display(self): print (self.Ino,"\t\t",self.name, '\t\t', self.Quantity,"\t\t",self.Rate,"\t",self.Amount) def create(): f=open("Item.dat","wb") n=int(input("Enter the no. of Items :")) s=Item() for i in range(n): def append(): s.storedata() f=open("Item.dat","ab") pickle.dump(s,f) n=int(input("Enter the no. of Items :")) f.close() s=Item() for i in range(n): s.storedata() pickle.dump(s,f) f.close() def insert(): f1=open("Item.dat","rb") f2=open("newfile.dat","wb") s1=Item() s1.storedata() end=0 try: while True: s= pickle.load(f1) if s.name<=s1.name: pickle.dump(s,f2) else : end=1 break pickle.dump(s1,f2) f1.seek(0) while True: s= pickle.load(f1) if s.name>s1.name: pickle.dump(s,f2) except EOFError: if end==0: pickle.dump(s1,f2) f1.close() f2.close() os.remove("Item.dat") os.rename("newfile.dat","Item.dat") def delete(): Ino=int(input("Enter the Item Number for deletion: ")) f1=open("Item.dat","rb") f2=open("newfile.dat","wb") status=0 try: while True: s= pickle.load(f1) if s.Ino!=Ino: pickle.dump(s,f2) else : status=1 except EOFError: f1.close() f2.close() os.remove("Item.dat") os.rename("newfile.dat","Item.dat") if status==1: print ('record deleted') else: print ('record not found') def modify(): Ino=int(input("Enter the Item Number whose details need to be modified : ")) f1=open("Item.dat","rb") f2=open("newfile.dat","wb") s=Item() status=0 try: while True: s= pickle.load(f1) if s.Ino==Ino: status=1 s.storedata() pickle.dump(s,f2) except EOFError: f1.close() f2.close() os.remove("Item.dat") os.rename("newfile.dat","Item.dat") if status ==1: print ('file modified') else: print ('record not found ') def search(): Ino=int(input("Enter the Item Number whose details to be searched : ")) f1=open("Item.dat","rb") status=0 try: while True: s= pickle.load(f1) if s.Ino==Ino: status=1 print ("Item Number : ",s.Ino) print ('Item name : ', s.name) print ('Quantity :',s.Quantity) print ('Rate : ', s.Rate) print ("Amount : ", s.Amount) except EOFError: f1.close() if status==0: print ('Recod not found') def display(): print (‘Item No\t\tName\t\tQuantity\tRate\t Amount') s=Item() f=open("Item.dat","rb") try: while True: s= pickle.load(f) s.display() except EOFError: f.close() def main(): create() while True: print ('\n\n1-Append file') print ('2-Insert a record') print ('3-Delete a Quantity') print ('4-Modify record') print ('5-Display details') print ('6-Search record') print ('7-Exit\n\n') ch = int(input('Enter your choice :')) if ch==1: append() elif ch==2: insert() elif ch==3: delete() elif ch==4: modify() elif ch==5: display() elif ch==6: search() elif ch==7: exit() else: print (' Wrong choice entered') main() Output: 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Enter the no. of Items :3 Enter Item Number : 1 Enter name: Laptop Enter Quantity: 10 Enter Rate : 2500 Enter Amount : 25000 Enter Item Number : 2 Enter name: Pen Enter Quantity: 50 Enter Rate : 10 Enter Amount : 500 Enter Item Number : 3 Enter name: Printer Enter Quantity: 10 Enter Rate : 1000 Enter Amount : 10000 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Enter your choice :5 Item No 1 2 3 Name Laptop Pen Printer Quantity 10.0 50.0 10.0 Rate 2500.0 10.0 1000.0 Amount 25000.0 500.0 10000.0 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Enter your choice :6 Enter the Item Number whose details to be searched : 2 Item Number : 2 Item name : Pen Quantity : 50.0 Rate : 10.0 Amount : 500.0 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Enter your choice :4 Enter the Item Number whose details need to be modified : 2 Enter Item Number : 22 Enter name: Pencil Enter Quantity: 30 Enter Rate : 5 Enter Amount : 150 file modified 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Enter your choice :5 Enter your choice :5 Item No Name 1 Laptop 22 Pencil 3 Printer Quantity 10.0 30.0 10.0 Rate 2500.0 5.0 1000.0 Amount 25000.0 150.0 10000.0 • • • • • • • • 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Enter your choice :2 Enter Item Number : 3 Enter name: Mouse Enter Quantity: 20 Enter Rate : 50 Enter Amount : 1000 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Enter your choice :5 Item No 1 3 22 3 Name Laptop Mouse Pencil Printer Quantity 10.0 20.0 30.0 10.0 Rate 2500.0 50.0 5.0 1000.0 Amount 25000.0 1000.0 150.0 10000.0 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Enter your choice :3 Enter your choice :5 Item No Name 1 Laptop 3 Mouse 3 Printer Enter the Item Number for deletion: 22 record deleted 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Quantity 10.0 20.0 10.0 Rate 2500.0 50.0 1000.0 Amount 25000.0 1000.0 10000.0 Enter your choice :2 Enter Item Number : 9 Enter name: Nothing Enter Quantity: 1 Enter Rate : 10 Enter Amount : 10 Enter your choice :5 Item No Name 1 Laptop 3 Mouse 9 Nothing 3 Printer 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Quantity 10.0 20.0 1.0 10.0 Rate 2500.0 50.0 10.0 1000.0 Amount 25000.0 1000.0 10.0 10000.0 Enter your choice :2 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Enter Item Number : 0 Enter name: Apple Enter Quantity: 5 Enter Rate : 1 Enter Amount : 5 Enter your choice :5 Item No Name 0 Apple Quantity 5.0 Rate 1.0 Amount 5.0 1 3 9 Laptop Mouse Nothing 10.0 20.0 1.0 2500.0 50.0 10.0 25000.0 1000.0 10.0 3 Printer 10.0 1000.0 10000.0 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Enter your choice :2 Enter Item Number : 100 Enter name: Zen Enter Quantity: 10 Enter Rate : 20 Enter Amount : 200 1-Append file 2-Insert a record 3-Delete a Quantity 4-Modify record 5-Display details 6-Search record 7-Exit Enter your choice :5 Item No Name Quantity Rate Amount 0 Apple 5.0 1.0 5.0 1 Laptop 10.0 2500.0 25000.0 3 Mouse 20.0 50.0 1000.0 9 Nothing 1.0 10.0 10.0 3 Printer 10.0 1000.0 10000.0 100 Zen 10.0 20.0 200.0 Write program to perfom the following operation on a binary file: 1-Append file 2-Modify record 3-Display details 4-Exit Consider the following class Customer: class Customer: def __init__(self): self.Cno=0 self.Name="" self.Mobile="" def Enter(self): ……… def Modify(self): self.Mobile=input("Enter a new mobile number ") def display(self): print (self.Cno,'\t',self.Name,'\t',self.Mobile) def GetCno(self): return self.Cno import pickle import os class Customer: def __init__(self): self.Cno=0 self.Name="" self.Mobile="" def Enter(self): self.Cno=int(input("Enter Candidate Number : ")) self.Name=input("Enter a name : ") self.Mobile=input("Enter mobile number ") def Modify(self): self.Mobile=input("Enter a new mobile number ") def display(self): print (self.Cno,'\t',self.Name,'\t',self.Mobile) def GetCno(self): return self.Cno def create(): def append(): f=open("CONTACT.DAT","wb") f=open("CONTACT.DAT","ab") n=int(input("Enter the no. of Customers :")) n=int(input("Enter the no. of Customers:")) s=Customer() s=Customer() for i in range(n): for i in range(n): s.Enter() s.Enter() pickle.dump(s,f) pickle.dump(s,f) f.close() f.close() def display(): print ('C.Np\t\tName\t\tMobile Number') s=Customer() f=open("CONTACT.DAT","rb") try: while True: s= pickle.load(f) s.display() except EOFError: f.close() def modify(): mobile=input("Enter mobile number of the Customer whose data needs to be modified : ") f1=open("CONTACT.DAT","rb") f2=open("newfile.dat","wb") s=Customer() status=0 try: os.remove("CONTACT.DAT") while True: os.rename("newfile.dat","CONTACT.DAT") s= pickle.load(f1) if status ==1: if s.Mobile==mobile: print ('file modified') status=1 else: s.Enter() print ('record not found ') pickle.dump(s,f2) except EOFError: f1.close() f2.close() def main(): create() while True: print ('\n\n1-Append file') print ('2-Modify record') print ('3-Display details') print ('4-Exit\n\n') ch = int(input('Enter your choice :')) if ch==1: append() elif ch==2: modify() elif ch==3: display() elif ch==4: exit() else: print (' Wrong choice entered') main() Output: Enter the no. of Customers :3 Enter Candidate Number : 1 Enter a name : aa Enter mobile number 111 Enter Candidate Number : 2 Enter a name : bb Enter mobile number 222 Enter Candidate Number : 3 Enter a name : cc Enter mobile number 333 1-Append file 2-Modify record 3-Display details 4-Exit Enter your choice :3 C.Np Name 1 aa 111 2 bb 222 3 cc 333 1-Append file 2-Modify record 3-Display details 4-Exit Mobile Number Enter your choice :2 Enter the Customer number whose mobile number needs to be modified : 222 Enter Candidate Number : 9 Enter a name : xxx Enter mobile number 999 file modified 1-Append file 2-Modify record 3-Display details 4-Exit Enter your choice :3 C.Np Name 1 aa 111 9 xxx 999 3 cc 333 1-Append file 2-Modify record 3-Display details 4-Exit Mobile Number Enter your choice :1 Enter the no. of Customers:1 Enter Candidate Number : 4 Enter a name : dd Enter mobile number 444 1-Append file 2-Modify record 3-Display details 4-Exit Enter your choice :3 C.Np Name 1 aa 111 9 xxx 999 3 cc 333 4 dd 444 1-Append file 2-Modify record 3-Display details 4-Exit Mobile Number