CS - Xii - SM - File Handling
CS - Xii - SM - File Handling
CS - Xii - SM - File Handling
Those data are to be retrieved later on,then the concept of file handling comes. It is
impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the file system which is not volatile
and can be accessed every time. File handling in Python enables us to create, update,
read, and delete the files stored on the file system through our python program. The
following operations can be performed on a file.
1. O
pen the file.
2. P
rocess file i.e perform read or write operation.
3. C
lose the file.
Types of File :
Text Files:
A file whose contents can be viewed using a text editor is called a text file. A text file
is simply a sequence of ASCII or Unicode characters. Python programs, contents
written in text editors are some of the example of text files.
Binary Files:
A binary file stores the data in the same way as as stored in the memory. The .exe
files,mp3 file, image files, word documents are some of the examples of binary
files.we can’t read a binary file using a text editor.
CSV Files:
CSV stands for Comma Separated Values. CSV is just like a text file, in a human
readable format which is extensively used to store tabular data, in a spreadsheet or
database. The separator character of CSV files is called a delimiter. Default delimiter
is comma (,). Other delimiters are tab (\t), colon (:), pipe (|), semicolon (;)
characters.
2. Open the file and assign its reference to a file object or file-handle.
3. Process the file as required : Perform the desired operation from the file.
4. Close the file.
Before any reading or writing operation of any file,it must be opened first of
all.Python provides built in function open() for it. It accepts two parameters :
filename, and mode.
Syntax:
<file_object_name> = open(<file_name>,<mode>)
Example: f = open(“demo.txt”,”r”)
File Objects:
Mode Description
“r” Read Default value. Opens a file for reading, error if the file
does not exist.
“w” Write Opens a file for writing, creates the file if it does not
exist
“a” Append Opens a file for appending, creates the file if it does
not exist
“r+” Read and File must exist otherwise error is raised.Both reading
Write and writing operations can take place.
“w+” Write and File is created if it does not exist.If the file exists past
Read data is lost (truncated).Both reading and writing
operations can take place.
“a+” Append and File is created if it does not exist.If the file exists past
Read data is lost (truncated).Both reading and writing
operations can take place.
CLOSING A FILE
close():
Used to close an opened file. After using this method, an opened file will be closed
and a closed file cannot be read or written any more. It is important to close your
files, as in some cases, due to buffering, changes made to a file may not show until
you close the file.
Syntax:
<fileObject>.close()
Example : f.close()
A Program reads a text/binary file from hard disk. Here File acts like an input to the
program.
read() METHOD
By default the read() method returns the whole text, but you can also specify how many
characters you want to return by passing the size as argument.
Syntax:
readline() METHOD
Syntax:
<file_object>.readline()
Example
f = open("demo.txt", "r")
print(f.readline())
#This program will return the first line in the file “demo.txt” irrespective of #number
of lines in the text file.
readlines() METHOD
readlines() method will return a list of strings, each separated by \n. readlines() can
be used to read the entire content of the file.
Syntax:
<file_object>.readlines()
Example :
f = open("demofile.txt", "r")
print(f.readlines())
The read() reads from a file in read mode, and stores its contents in a string type
variable. It can either read the whole content from the file if a parameter is not passed and
reads only as many characters as the size passed to the read().
The readline() function reads from a file in read mode and returns the next line in the file or
a blank string if there are no more lines. The return data type is of string type.
The readlines() function, also reads from a file in read mode and returns a list of all lines in
the file. The returned data is of list type.
A Program writes into a text/binary file in hard disk.Followings are the methods to
write a data to the file:
o write () METHOD
o writelines() METHOD
If
you open a file in in “w” or write mode , Python overwrites an existing file or
creates a non- existing file. For an existing file with the same name , the earlier data
gets lost.
If
you want to write into a file while retaining the old data , the file must be opened in
append or “a” mode.
write() Method
write() method takes a string ( as parameter ) and writes it in the file. For
storing data with end of line character, you will have to add \n character to
end of the string.
Example:
f = open("demo_write.txt", "a")
f.close()
f = open("demo_write.txt", "r") #open and read the file after the appending
print(f.read())
writelines() METHOD
For writing a string at a time, we use write() method, it can't be used for
writing a list, tuple etc. into a file. Python file method writelines() writes
a sequence of strings to the file. The sequence can be any iterable object
producing strings, typically a list of strings.So, whenever we have to
write a sequence of string / data type, we will use writelines(),
instead of write().
f = open("demofile.txt", "a")
f.close()
f = open("demofile.txt", "r")
print(f.read())
The flush() function:
When you write on to a file using any of the write functions, Python
holds everything to write in the file and pushes it onto actual file on
storage device at a later time. So to force Python t write the contents onto
files you can use flush().
Syntax :
<file_object>.flush()
f = open("demo_flush.txt","w+")
f.write("India is my country.\n")
f.flush()
x = "Jai Hind"
f.write(x)
f.close()
BINARY FILES:
Files that store objects as some byte stream are called binary files. That is, all the
binary files are encoded in binary format , as a sequence of bytes, which is understood
by a computer or machine. In binary files, there is no delimiter to end the line. Since
they are directly in the form of binary, there is no need to translate them. But they are
not in human readable form and hence difficult to understand.
Python objects (list, dictionary etc) have a specific structure which must be
maintained while storing or accessing them. Python provides a special module called
pickle module for this. PICKLING refers to the process of converting the structure
to a byte stream before writing to a file. The process to converts any kind of python
objects (list, dict, etc.) into byte streams (0s and 1s) . UNPICKLING is used to
convert the byte stream back to the original structure while reading the contents of
the file.
PICKLE Module
Before reading or writing to a file, we have to import the pickle module.
import pickle
pickle.dump() method is used to write the object in file which is opened in binary access
mode.
Syntax :
pickle.dump(<structure>,<FileObject>)
Here Structure can be any sequence in Python such as list, dictionary etc. FileObject is the
file handle of file in which we have to write.
import pickle
f = open("binary_file1.dat","wb")
city = ["Banglore","Delhi","Hyderabad"]
pickle.dump(city,f)
f.close()
pickle.load() Method
pickle.load() method is used to read data from a file
Syntax :
<structure> = pickle.load(<FileObject>)
import pickle
f=open("binary_file1.dat","rb")
lst = pickle.load(f)
print(lst)
f.close()
CSV FILES :
CSV stands for Comma Separated Values. It is a type of plain text file that uses
specific structuring to arrange tabular data such as a spreadsheet or database.
CSV like a text file , is in a human readable format and extensively used to store
tabular data, in a spreadsheet or database. Each line of the file is a data record. Each
record consists of one or more fields, separated by commas. The separator character
of CSV files is called a delimiter. Default delimiter is (,). Other delimiters are tab(\t),
colon (:), pipe(|), semicolon (;) characters.
To read data from csv files, reader function of csv module is used. csv.reader()
returns a reader object.It loads data from a csv file into an iterable after parsing
delimited data.
STEPS TO READ
import csv
2. O
pen csv file in read mode.
f = open(“csv_demo.csv”,”r”)
3. C
reate the reader object.
demo_reader = csv.reader(f)
4. F
etch data through for loop, row by row.
5. C
lose the file
f.close()
# Program to read from a csv file
import csv
f = open("emp.csv","r")
emp_reader=csv.reader(f)
print(row[0],row[1],row[2])
# print(row) : As a list
f.close()
To write data into csv files, writer() function of csv module is used.
csv.writer():
The csv.writer() returns a writer object that converts the data into a delimited
string.The string can be later converted into csv files using the writerow() or
writerows() method.
Syntax:
<writer_object>.writerow() :
import csv
f=open("emp.csv","w",newline="")
emp_writer = csv.writer(f)
emp_writer.writerow(["EmpName","EmpID","Dept"])
emp_rec = []
while True:
emp_rec.append([empname,eid,dept])
if ch == "N" or ch =="n":
break
emp_writer.writerows(emp_rec)
## emp_writer.writerow(i)