CLASS-12-FILE_HANDLING-1
CLASS-12-FILE_HANDLING-1
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.
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.
• 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()
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
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.