diff --git a/file_handling.py b/file_handling.py index 5c41621..45d8faf 100644 --- a/file_handling.py +++ b/file_handling.py @@ -36,6 +36,8 @@ file.close ## using write with with() +# the advantage of using with is that it ensures the file is closed +# after nested block of code is ran with open('trial.txt','r+') as file: text = file.read() diff --git a/file_handling_2.py b/file_handling_2.py index fb9be83..eae27c3 100644 --- a/file_handling_2.py +++ b/file_handling_2.py @@ -21,7 +21,7 @@ filenew = open("student.dat" , "w") No_of_stdnt = int(input("enter the no of students in class :")) for i in range(No_of_stdnt): - name = input("Enter the name of the studnet :") + name = input("Enter the name of the student :") roll = int(input("enter the roll no of the student :")) Marks = int(input("eneter the marks obtained by the student :")) data = str(roll) + "," + name + "," + str(Marks) + '\n' diff --git a/file_handling_3.py b/file_handling_3.py index e69de29..32a0a9c 100644 --- a/file_handling_3.py +++ b/file_handling_3.py @@ -0,0 +1,42 @@ +### continued ........... +## File pointer ( analogous to a bookmark in a book ) + +import sys +import os + +## infile = open("filename","r") would open the file and put the file +# pointer at the beginning of the file +# ch = infile.read(1) would read 1 byte (one character) from the file +# str = infile.read(2) would read 2 bytes from the place where the +# file pointer left + +############################################# +### WORKING WITH BINARY FILES ### +############################################# + +import pickle + +# pickling / serialisation = converting an python object into a byte-stream +# unpickling / deserialization = converting the byte stream again into python object +## the pickle module has dump() and load() methods to write and read to and from a file +# Creating / opening / closing binary files +# + +dfile = open("student_new.dat","ab") # b specifies to open it in binary mode +data = {} ## creating an empty dictionary +No_of_stdnt = int(input("enter the no of students in class :")) +for i in range(No_of_stdnt): + name = input("Enter the name of the student :") + roll = int(input("enter the roll no of the student :")) + marks = int(input("eneter the marks obtained by the student :")) + data['Name'] = name + data['Roll'] = roll + data['Marks'] = marks + ## the above three lines fillup the dictionary + pickle.dump(data,dfile) + +dfile.close() + + + + diff --git a/student_new.dat b/student_new.dat new file mode 100644 index 0000000..e71a9cb Binary files /dev/null and b/student_new.dat differ