File Handling
File Handling
Suppose you are playing a video game, and after some time, you want to close it. So, the
program should be able to store the current state of the game, including current level/stage,
your score, etc. as a Python object. Likewise, you may like to store a Python dictionary as an
object, to be able to retrieve later.
To save any object structure along with data, Python provides a module called Pickle. The
module Pickle is used for serializing and de-serializing any Python object structure.
Pickling is a method of preserving food items by placing them in some solution, which
increases the shelf life. In other words, it is a method to store food items for later
consumption
• Serialization is the process of transforming data or an object in memory
(RAM) to a stream of bytes called byte streams. These byte streams in a
binary file can then be stored in a disk or in a database or sent through a
network. Serialization process is also called pickling.
• De-serialization or unpickling is the inverse of pickling process where a
byte stream is converted back to Python object.
READ
EOF error
• This error is likely to occur when:
• we fail to declare a statement for loop
(while/for)
• we omit the closing parenthesis or curly
bracket in a block of code.
• If file is not properly closed
Write
append
Search
Update
delete
Opening/Closing csv files
• Open a csv file:
f=open(“stu.csv”,”w”)
Or
f=open(“stu.csv”,”r”)
• Close a csv file:
• f.close()
Since CSV files are delimited flat files and before
writing onto them, the data must be in a CSV-
Writeable-delimited-form, it is important to
convert the received user data into the form
appropriate for the csv files. This task is performed
by the writer object. The data row written to a
writer object(written using writerow() or
writerows() function) gets converted to csv
writeable delimited form and then written on to
the linked csv file on the disk.
Writerow() without newline and delimiter
Writerow() with newline
Writerow() with delimiter
Follow the steps given below to space out the
columns in spreadsheet:
1. Click->data->from text(import python file of
csv code)->locate csv file ->import
2. Click next
3. Check semicolon checkbox ->finish
4. Choose option newworksheet
Writerows()
Reading in a csv files
Reading from a csv file involves loading of a csv
files’s data, parsing it(i.e, removing its
delimitation), loading it in a python iterable
and then reading from this iterable.
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. The csv.reader object loads
data from the cvs file, parses it, i.e., removes
the delimiters and returns the data in the form
of a python iterable where from you can fetch
one row of data at a time.