We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32
CONTENT
• WORKING WITH BINARY FILES
• CREATINC/OPENING/CLOSING BINARY FILES • WRITING ONTO A BINARY FILE – PICKLING • APPENDING RECORDS IN BINARY FILES • READING FROM A BINARY FILE • SEARCHING IN A FILE • UPDATING IN A BINARY FILE CONTENTS • ACCESSING AND MANIPULATING LOCATION OF FILE POINTER • THE TELL( ) • THE SEEK( ) • UPDATING RECORDS IN A FILE • WORKING WITH CSV FILES • OPENING AND CLOSING CSV FILES • ROLE OF ARGUMENT NEWLINE IN OPENING CSV FILES CONTENT • WRITING IN CSV FILES • THE WRITEROWS() FUNCTION • READING IN CSV FILES WORKING WITH BINARY FILES • Objects have some structure or hierarchy associated, it is important that they are stored in way so that their structure or hierarchy is maintained. • Objects are often serialized and then stored in binary files. • Serialization also called Pickling is a process of converting Python object hierarchy into a byte stream so that it can be written into a file. Pickling converts n object in byte stream in such a way that it can be reconstructed in original form when unpickled or de-serialized. • Unpickling is the inverse of pickling where a byte stream is converted into an object hierarchy. Unpickling produces the extra replica of the original object. WORKING WITH BINARY FILES • The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. • We must first import it in the program using import statement: import pickle • We can use dump( ) and load( ) methods of pickle module to write and read from an open binary file respectively. • Process of working with binary files is 1. import pickle 2. Open binary file in the required file mode 3. Process binary file by writing/reading objects using pickle modules method 4. Once done, close the file. CREATING / OPENING / CLOSING BINARY FILES .A Binary file is opened in the same way as we open any other files, but we need to make sure to use "b" with file modes to open a file in binary mode. Ex: Dfile = open("stu.Dat", "wb") or Filel = open("stu.dat", "rb") • Binary file will be created when opened in an output file mode and it does not exist already. • An open binary file is closed in the same manner as we close any other file as: Ex: Dfile.close( ) WRITING ONTO A BINARY FILE- PICKLING • To write an object on to a binary file opened in the write mode. we use dump( ) function of pickle module. • Syntax: pickle.dump(<object-to-be-written>. <file handle-of-open-file>) • Example: pickle.dump(list1. file1) pickle.dump(student1. file2) READING FROM A BINARY FILE • Once file is written using dump() module. we need to read from the file using load( ) function of pickle module as it would then unpickle the data coming from the file. • The load( ) function is used as per the following <object> = pickle.load(<filehandle>) • Example 1: nemp= pickle.load(fout) • Example 2: fin = open(‘Stu.dat’, ”rb”) .... …. stu = pickle.load(fin) READING FROM A BINARY FILE • It is important to know that pickle.load( ) function would raise EOFErrors when we reach end-of-file while reading from the file. • We can handle by using one of the below given two methods: 1. Use try and except blocks 2. Using with statement APPENDING RECORDS IN BINARY FILES • Appending records in binary files is similar to writing, we must open the file in append mode. • A file opened in append mode will retain the previous records and append the new records written in the file. • Example: student = open('Stu.dat’, "ab”) SEARCHING IN A FILE • There are multiple ways of searching for a value stored in a file. The simplest is sequential search using key in the read record. • Following has to be followed in order to search 1. Open the file in read mode 2. Read the file contents record by record 3. In every read record. look for the desired search key 4. If found, process as desired SEARCHING IN A FILE 5. If not found. read the next record and look for the desired search key. 6. If search-key is not found in any of the records. report that no such value found in the file. • Example: fin = open(“stu.dat“, "rb’) # open binary file in read mode searchkeys = [12, 14] # list contains key values to be searched for ….. ….. if stu['Rollno’] in searchkeys: #searching for in the read record UPDATING IN A BINARY FILE • Updating records in a file is similar and is a three step process: 1. Locate the record to be updated by searching for it 2. Make changes in the loaded record in memory 3. Write back onto the file at the exact location of old record ACCESSING AND MANIPULATING LOCATION OF FILE POINTER • Python provides two functions that help to manipulate the position of file- pointer and we can read and write from desired position in the file. • The two file pointer location functions of python are: 1. tell( ) 2. seek( ) THE TELL() • The tell( ) function returns the current position of the file pointer in the file.
• It is used as per the syntax:
<file-object>.tell( ) Where file-object is the file handle of the open file THE TELL() • Example: fh = open("Marks.txt". "r") print("Initially file pointers position is at : ", fh.tell( )) print(“3 bytes read are:”, fh.read(3)) print(“after previous read, current position of file-pointer:”, fh.tell()) The output for above code: Initially file pointers position is at : 0 3 bytes read are:12, After previous read, current position of file-pointer: 3 THE SEEK() • The seek( ) function changes the position of the file-pointer by placing the file pointer at the specified position in the open file. • Syntax: <file-object>.seek(offset,[mode]) where offset is a number specifying number of bytes mode is a number 0 or 1 or 2 signifying file object is the file handle of open file THE SEEK() • Example: fh = open("Marks.txt", "r") …. …. fh.seek(30) #file pointer at 30 byte from the beginning of the file(default) fh.seek(30, 1) #current position file pointer mode=1 fh.seek(-30, 2) # file pointer at 30 bytes backward end of file mode=2 fh.seek(30, 0) # file pointer at 30 byte from beginning mode=0 fh.seek(-5, 1) #file pointer at 5 bytes behind backward direction from current file pointer position mode=1 THE SEEK() It is clear that you can move file pointer in forward direction (with positive value for bytes) and backward direction (negative value for bytes) • Backward movement of file pointer is not possible from the beginning of the file (BOF). • Forward movement of file –pointer is not possible from end of file(EOF). WORKING WITH CSV FILES • The CSV files are popular because of these reasons: 1. Easier to create 2. Preferred export and import format for databases and spreadsheets 3. Capable of storing large amounts of data OPENING AND CLOSING CSV FILES • A CSV file is opened in the same way as we open any other text file, but we should make sure to do the following things: 1. Specify the file extension as .csv 2. Open the file like other text files Dfile = open("stu.csv“, "w") or filel = open("stu.csv“, "r") 3. An open CSV file is closed in the same manner as we close other files Dfile.close( ) ROLE OF ARGUMENT NEWLINE IN OPENING CSV FILES • EOL characters used in different operating system are:
WRITING IN CSV FILES WRITING IN CSV FILES • Before writing the data it must be in csv-writable-delimited-form, it is important to convert the received user data into the form approriate for the csv files. • This task is performed by writer object. • The data row written to a writer object(using writerow() or writerows() functions) gets converted to csv writable delimited form and then written on the disk WRITING IN CSV FILES WRITING IN CSV FILES 1. Import csv module 2. Open csv file in a file-handle ex: fh = open(“student.csv”, “w”) 3. Create writer object by using syntax <name-of-writer-object> = csv.writer(<file-handle>,[delimiter = delimiter character>]) ex: stuwriter = csv.writer(fh) or stuwriter = csv.writer(fh, delimiter = ‘ |’) 4. Obtain user data and form python saequence(list or tuple)out of it ex: sturec =(11, “neelam”,79.0) 5. Write the python sequence containing user data onto the writer object using csv.writerow() or csv.writerows(). ex: csv.writerow(sturec) 6. Once done close the file THE WRITEROWS() FUNCTION • If we have all the data available and data is not much lengthy then it is possible to write all data in one go. • We need to create a nested sequence out of data and then write using the writerows( ) function. • The writerows( ) method writes all given rows to the csv file to write the following nested sequence. we can use the writerows( ) function: sturec = [ [11, Nistha, 79.0], [12, Rudy, 89.0], [13, Rustom, 75.0] ] <writerobject>.writerows(sturec) READING IN CSV FILES • Reading from a csv file involves loading of a csv file's data. parsing it, loading it in a python iterable and then reading from the iterable. • python sequence that can be iterated over in a for loop is a python iterable. E.g .. Lists, tuples and strings • Following function is used to read from csvfiles: • csv.reader( ) : returns a reader object which loads data from CSV file into an iterable after parsing delimited data. • The csv.reader object does the opposite of csv.writer object. • CSV.reader loads data from the csv file, parses it, and returns the data in the form of a python iterable. READING IN CSV FILE Reading in csv files 1. Import csv module 2. Open csv file in a file-handle in read mode <file handle> = open (<csv-file>, <read mode>) e.g: fh = open("student.csv", "r") The file being opened must already exist otherwise an exception will get raised. Your code should be able to handle the exception i.e ., through try .. except. (Alternatively you can use the with statement as mentioned below.) READING IN CSV FILES 3. Create the reader object by using the syntax <name-of-reader-object> = csv.reader(<file-handle>, [delimiter =<delimiter character>]) e.g., stureader = csv.reader (fh) OR stureader = csv.reader (fh, delimiter = ‘|’) 4. The reader object stores the parsed data in the form of iterable and thus you can fetch from it row by row through a traditional for loop, one row at a time : for rec in stureader : print (rec) 5. Process the fetched single row of data as required. 6. Once done, close the file.