0% found this document useful (0 votes)
15 views4 pages

CLASS-12-FILE_HANDLING-1

Files are essential for storing large amounts of data permanently and facilitate data sharing between programs. Different types of files include text files, binary files, and CSV files, each with specific characteristics and handling methods in Python. File handling in Python involves opening, processing, and closing files, with various modes available for reading and writing data.

Uploaded by

sangaara260
Copyright
© © All Rights Reserved
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
0% found this document useful (0 votes)
15 views4 pages

CLASS-12-FILE_HANDLING-1

Files are essential for storing large amounts of data permanently and facilitate data sharing between programs. Different types of files include text files, binary files, and CSV files, each with specific characteristics and handling methods in Python. File handling in Python involves opening, processing, and closing files, with various modes available for reading and writing data.

Uploaded by

sangaara260
Copyright
© © All Rights Reserved
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/ 4

Why files are Used?

Files are used to store huge collection of data and records permanently. Many applications require
large amount of data. In such situation, we need to use some devices such as hard disk, compact
disc etc., to store the data.

Need for a data file


• It is a convenient way to deal with large quantities of data.
• To avoid input of data multiple times during program execution.
• To share data between various programs.

Types of file:
• Text files: Text files store information in ASCII or Unicode characters. In text file, each line of text
is terminated, (delimited) with a special character known as EOL (End of Line) character.
• Binary files: Binary files are just files that contain information in the same format in which the
information is held in memory, i.e., in binary file, there is no delimiter for a line.
• CSV files: CSV (Comma Separated Value) files are a common file format for transferring and
storing data. CSV is a widely used format that stores tabular data (numbers and text) as plain text. It
is a delimited text file that uses a comma to separate values.

In Python, File Handling consists of following three steps:


• Open the file.
• Process file i.e perform read or write operation.
• Close the file.

Basic Operations on a Text File


• Open a text file: Files in Python can be opened with a built-in open() function. The open() function
creates a file object which would be utilized to call other methods associated with it.
Syntax:
file_object=open(filename[ access_mode],[ buffering])
Here is the parameter details:
• filename: The file name argument is a string value that contains the name of the file that you
want to access.
• access_mode: The access_mode determines the mode in which the file has to be opened. This is
optional parameter and the default file access mode is read (r).

File Opening Modes


MODES DESCRIPTION
r Opens a file for reading only in text format. This is the default mode.
rb Opens a file for reading only in binary format. This is the default mode.
r+ Opens a file for both reading and writing.
Opens a file for both reading and writing in binary format. The file pointer will be at the
rb+
beginning of the file.
Opens a file for writing only. Overwrites the file, if the file exists else creates a new file for
w
writing.
Opens a file for writing in binary format. Overwrites the file, if the file exists else creates a
wb
new file for reading and writing.
Opens a file for reading as well as writing. Overwrites the file if it already exists and
w+
creates a new file if it doesn't exist.
Opens a file for writing as well as reading in binary mode. Overwrites the file if it already
wb+
exists and creates a new file if it doesn't exist.
Opens a file for appending. Append new data at ends. If the file does not exist, it creates a
a
new file for writing.
Opens a file for appending in binary format. Append new data at ends. If the file does not
ab
exist, it creates a new file for writing.
Opens a file for both appending and reading. Append new data at ends. If the file does not
a+
exist, it creates a new file for reading and writing.
Opens a file for both appending and reading in binary format. Append new data at ends.
ab+
If the file does not exist, it creates a new file for reading and writing.

• Close a text file: after opening and performing the reading, writing operations, it is important to
close the file. This is done using .close() method.
Syntax:
file.close()

Reading and Manipulation of data from a text file


Before start reading the file, we must open the file in ‘r’ mode. There are three ways in which we
can read the files in python.
• read([n]): Read the entire file into a string.
Syntax:
file. read([n])
• readline([n]): Read next line (upto and include newline) and return a string (including newline). It
returns an empty string after the end-of-file (EOF).
Syntax:
file. readlines([n])
• readlines():Read all lines into a list of strings.
Syntax:
file. readlines([n])

We have two methods for writing data


• write(string): Write the given string to the file and return the number of characters written. You
need to explicitly terminate the string with a '\n', if needed.
Syntax:
file.write(string)
• writelines(list): Using this function we can give list of lines to write into the file. The important
thing to remember here is you have to give ‘\n’ manually at the end of each line in the list to tell the
python to write it into separate lines.
Eg. [‘1st Line \n’, ‘2nd Line \n’, ‘3rd Line’]
Syntax:
file. writelines(list)

Appending data into a text file


To append data into a file we must open the file in ‘a+’ mode so that we will have access to both the
append as well as write modes. For example, consider we already have a file “text1.txt” with data
written “I am in class-XII.”. Let’s perform append operation on that file.
f.open(“text1.txt”, ‘a’)
f.write(“I am a cricket player.”)
f.close()
Output: I am in class-XII. I am a cricket player.
Basic Operations on a Binary File
Opening and closing of binary file is same as text file opening and closing. The "rb" mode opens the
file in binary format for reading, while the "wb" mode opens the file in binary format for writing.
Pickle Module
Pickle module provides us with the ability to serialize and de-serialize objects, i.e., to convert
objects into bitstreams which can be stored into files and later be used to reconstruct the original
objects.
dump and load Methods:
Pickle module contains a dump() function to perform pickling and pickle module contains load()
function to perform unpickling.
Syntax of dump():
dump(data_to_dump, file_object)
Where data_to_dump is the object that has to be dumped to the file with the file named file_ object.
Syntax of load():
store_object = load(file_object)
Here, the pickled Python object is loaded from the file having a file handle named file_object and is
stored in a new file handle called store_object.
Read from and Write/Create into a binary file:
Python provided read ( ) and write( ) methods works with string parameters and will not
directly work with binary files. Conversion of data at the time of reading and writing is required.
dump() method is used to write the objects in a binary file and load() method is used to read data
from a binary file.
Append and Update operations in a binary file:
To append the data to the binary file, open a file in 'ab' mode. A file opened in append mode will
retain the previous records and append the new records at the end of the file.

In order to update a binary file, one must know the position of file pointer. To Check out the
position of the file pointer, we use two file pointer location functions: tell() and seek().
tell( ) function: The tell( ) function returns the current position of the file pointer in the file.
Syntax:
<fileobject>.tell( )
• seek( ) function: The seek ( ) function changes the position of the file pointer by placing the file
pointer at the specified position in the open file.
Syntax:
<fileobject>.seek( offset[,mode])
Where
offset =======>is number specifying number of bytes
mode =======> is number 0 or 1 or 2
0 for beginning of file, 1 current position of file pointer, 2 end of file

Import CSV Module


In Python, to work with CSV files, we need to import the CSV module, an inbuilt module. To do this,
we need to use the “import” keyword before “csv” to support CSV files in python. The CSV module
includes all the necessary functions built in. They are:
• csv.reader
• csv.writer

Basic operations on a CSV file


• Open a CSV file: The CSV file is opened as a text file with Python’s built-in open() function, which
returns a file object.
• Close a csv file: Closing of binary file is same as text file closing.
• Read from a csv file: Reading from a CSV file is done using the reader object. The CSV file is
opened as a text file with Python’s built in open() function, which returns a file object.
• Write into and read from a csv file using csv.reader ( ) and csv.writerow( )
For reading, we open the file in ‘r’ mode and create newFile like object, further we create
newfilereader object using csv.reader() method to read each row of the file.
The csv.reader method returns a reader object which iterates over lines in the given CSV file.
• Optional Python CSV reader Parameters
Delimiter specifies the character used to separate each field. The default is the comma (‘,’).

Similarly, for writing, we open file in ‘w’ writing mode using open() method which create newFile
like object. When you have a set of data that you would like to store in a CSV file you have to use
csv.writer() function. To iterate the data over the rows(lines), you have to use the csv.writerow()
function.

You might also like