0% found this document useful (0 votes)
7 views26 pages

File handling in Python

The document provides an overview of file handling in Python, explaining the need for file handling, types of files (text and binary), and their differences. It outlines the steps involved in file handling, including opening, performing operations, and closing files, along with methods for reading and writing data. Additionally, it discusses various file modes and the use of functions like seek() and tell() for random access in files.
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)
7 views26 pages

File handling in Python

The document provides an overview of file handling in Python, explaining the need for file handling, types of files (text and binary), and their differences. It outlines the steps involved in file handling, including opening, performing operations, and closing files, along with methods for reading and writing data. Additionally, it discusses various file modes and the use of functions like seek() and tell() for random access in files.
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

FILE HANDLING IN

PYTHON
CLASS XII
(2025-26)
WHY THERE IS A NEED OF FILE HANDLING?

• A file in itself is a bunch of bytes stored on some


storage device.
• File helps us to store the data permanently, which
can be retrieved for future use.
TEXT FILES

• Stores information in ASCII or Unicode characters


• Each line of text is terminated with a special character known as EOL (End of
Line) (\n, \r)
• Internal translations take place when EOL is read
• Extension for text file is .txt
• Default mode of file
Text Files

Regular Text Files


Delimited Text Files

TSV (Tab Separated CSV (Comma


Values) Separated Values)
BINARY FILE

• Contains information in the same format in which the information is held in


memory.
• There is no delimiter for a line
• No translations are required.
• Faster than text files
• More secure.
DIFFERENCE BETWEEN TEXT FILES AND BINARY
FILES
• Text files stores information in ASCII • Used to store binary data such as
characters images,audio, video and text
• Each line of text is terminated with a special • No delimiter in Binary file
character known as EOL (End of Line) • Binary files are difficult to understand.
• Text files are easy to understand because these • Binary files are faster and easier for a
files are in human readable form. program to read and write than the text files
• Slower than Binary files • Have extension .dat
• Have extension .txt
CSV FILES

• Comma Separated Values (CSV) file


• Simple file in human readable format
• Used to store tabular data in plain text
• By default, delimiter is comma
• Easy to generate and import onto a spreadsheet or database
STEPS IN FILE HANDLING

Opening Performing Closing

Opening a file Performing Closing a file


Firstly, open the file operations on file At the end, close the
by specifying the After opening the file
name of the file and file, we can perform
the mode in which various operations on
you want to open the
the file: reading,
file
writing, appending,
searching, deleting
etc.
OPENING A TEXT FILE

• Two methods to open a file


✓Using open() function
✓Using with statement
HOW TO OPEN A TEXT FILE?

FileObject=open(<filename>)
OR
FileObject=open(<filename>,<mode>)
By default mode is ‘r’
HOW TO OPEN A TEXT FILE?

• Using with statement


This method is very handy when you have two related operations which
you would like to execute as a pair, with a block of code in between.
Syntax:
with open(<filename>,<fileMode>) as <File Handle>:
[Link](“…….”)
BENEFITS OF USING WITH STATEMENT

• It automatically closes the file after the nested block of code.


• It also handles all the exceptions also occurred before the end of block
POINTS TO REMEMBER

• The default file open mode is read mode


• If mode is not specified, python will open in read mode
• When you open a file in read mode, the given file must exist in the folder,
otherwise python will raise FileNotFoundError
READING DATA FROM FILES

• read() – reads at most n bytes, if n is not specified reads the


entire file. Returns string
• readline() – reads a line of input, if n is specified, reads n bytes –
returns string ending with ‘\n’ character. Returns blank string if
no more bytes are left for reading in the file.
• readlines() – returns all line of text, returns in the form of list.
Mode Description
r Opens file for in read only mode. This is the default mode
rb Opens file for read only mode in Binary format.
r+ Opens a file for reading and writing
rb+ Opens a file for both reading and writing in binary format
w Opens a file for writing only. Overwrites the file if already exist, else creates a new file
wb Opens a file for writing only in binary format
w+ Opens afile for both reading and writing
wb+ Opens a file for both reading and writing in binary format
a Opens a file for appending. The file pointer is at the end of the file if the file exists. If the file
does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format
a+ Opens a file for both appending and reading
ab+ Opens a file for both appending and reading in binary format
TO WRITE DATA INTO A FILE (W)

• If file doesn’t exists, it will create a new file.


• If file exists, it will overwrite the data in the file.
➢write()
➢writelines()
WRITE(STRING)

• write() takes a string and writes it in the file


• For storing data, with EOL character, we have to add ‘\n’ character
to the end of the string.
• For storing numeric value, we have to either convert it into string
using str() or write in quotes
WRITELINES(SEQUENCE)

• writelines() method is used to write sequence data types in


a file (string, list, tuples etc)
APPENDING DATA INTO A FILE

• Append means to add the data at the end of the file using
‘a’ mode
• If file doesn’t exists, it will create the new file.
• If file exists, it will append the data at the end of a file.
CLOSING FILES

• A close() breaks the link of file object and the file on the disk.
• After close(), no tasks can be perfomed on that file through file object or
file handle
Syntax:
[Link]()
Eg: [Link]()
COMPARING R+ AND W+

R+ MODE W+ MODE
• Used for both reading and writing • Used for both reading and writing.
• In r+ mode, file pointer is at the beginning of the • In w+ mode, file pointer is at the end of the
file. file.
• If file does not exists, it will display the • If the file does not exist, it will create the new
FileNotFound Error file.
• If the file exist, it doesn’t show any error. • If the file exist, it will overwrite the content.
RANDOM ACCESS IN FILES - seek(), tell()

• seek() – is used to change the position of the file pointer


to a given specific position.
• File pointer is like a cursor, which defines from where the
data has to be read or written into the file.
• Syntax: [Link](offset, from_what) #f is the file pointer
from_what can have 3 arguments
0 – Sets the reference point at the beginning of the file.
This is the default value.
1 – Sets the reference point at the current file position.
2 – Sets the reference point at the end of the file.

If offset is positive reads the file forward. If offset is


negative reads the file backwards.
Note:
But in python 3.x and above, we can
seek from beginning only if file is opened
in text mode. We can overcome this by
opening the file in ‘b’ mode.
tell()

• Tells the current position of the cursor.

You might also like