0% found this document useful (0 votes)
6 views36 pages

File Handling - PK

Uploaded by

LOLBOI
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)
6 views36 pages

File Handling - PK

Uploaded by

LOLBOI
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/ 36

DATA FILE HANDLING

FILE
 File is a collection of data stored on the secondary storage device with a name
called file name. The data stored within the file can be read, modified and
deleted through program using different File I/O functions or methods
provided by the language.
 So far, we have been accessing the data from the console input device and
storing into the variables and presenting the processed data onto the console
output device. It is OK for learning and experimenting with Python but
doesn’t enough to develop common business applications.
 It is because memory of variables allocate in the primary memory (RAM).
Data stored in the variables would be lost on completion of program
execution.
 The main purpose of any business application is to store the data
permanently for future reference. It is only possible by storing the
information (processed data) on any secondary storage device as a file.
NEED FOR FILES

 So far, we have been accessing the data from the console input device and
storing into the variables and presenting the processed data onto the console
output device. It is OK for learning and experimenting with Python but
doesn’t enough to develop common business applications.
 It is because memory of variables allocate in the primary memory (RAM).
Data stored in the variables would be lost on completion of program
execution.
 The main purpose of any business application is to store the data
permanently for future reference. It is only possible by storing the
information (processed data) on any secondary storage device as a file.
BEHIND THE SCENE

write()
input() f Story.txt
……………
User Input RAM …………….
Output
Secondary Storage
print() Ex. HardDisc
read()
TYPES OF DATA FILES
 Text Files: Text files are structured as a sequence of lines, where each line
includes a sequence of characters (i.e. stored based on ASCII value). It can be
edited in any text editor program.

 Binary Files : A binary file is a file stored in binary format (i.e. combination
of one’s and zero's).
FILE OBJECT ATTRIBUTES
Once a file is opened and you have one file object, you can get various information related
to that file.
Here is a list of all attributes related to file object:

Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
Python
file.name Returns name of theProgram
file.
OPENING AND CLOSING FILES
Here the point is that the file “Hello.txt” which is used here is pre
built and stored in the same folder where Python is installed.

Opened the File

File is closed

A program describing the functions of file handling. Output


STEPS TO READ FROM OR WRITE TO A FILE:

 Step 1: Open a file using open( ) function

 Step 2: Read or Write using File Methods.

 Step 3: Close the file.


OPENING A FILE
To work with a file, first of all you have to open the file. To open a file
in python, we use open( ) function.
Syntax:
file_objectname= open(filename, mode)
Example:
f2= open("Notes.txt", "w")

CLOSING A FILE
After performing the operations, the file has to be closed. For this, a close( )
function is used to close a file.
Syntax:
file-objectname.close( )
Example:
f2.close()
FILE MODES
Text File Binary Description
Mode File Mode
r rb Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.
w wb Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
a ab Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.
r+ rb+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.

w+ wb+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for writing and reading.

a+ ab+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for
writing and reading.
BASIC OPERATIONS WITH FILES

 Read the data from a file


 Write the data to a file
 Append the data to a file
 Delete a file
 Deleting Data from File.
 Copying of File.
 Updating Data into File.
READ THE DATA FROM A TEXT FILE:

 read( ) : reads n bytes. if no n is specified, reads the entire file. Returns a


string containing either n bytes or entire file

 readline( ) : Reads a line. if n is specified, reads n bytes. Returns a string


containing the line.

 readlines( ): Reads all lines and returns a list of lines.


USE OF READ METHOD 1
USE OF READ METHOD2
USE OF READLINE METHOD1
USE OF READLINE METHOD2
USE OF READLINES METHOD
READING USING FILE OBJECT
CHARACTER FETCHING USING READ METHOD
WORD FETCHING USING READ
LINE FETCHING USING READLINES
LINE FETCHING USING FILE OBJECT
WRITE DATA TO A TEXT FILE

 write( ):Write the data to a file.


Syntax:
write(string)

 writelines( ): Write all strings in a list L as lines to file.


Syntax:
writelines(L)

Note: We have to add ‘\n’ for end of line to the string ourselves, otherwise
entire string will be written in one line.
USE OF WRITE METHOD
USE OF WRITELINES METHOD
APPEND THE DATA TO A TEXT FILE
 This operation is used to add the data in the end of the file. It doesn’t overwrite
the existing data in a file.

USE OF APPEND MODE


CURRENT WORKING DIRECTORY

RENAME A FILE
To rename a file, you have to import the os module, and use rename( )
function.

Example:
>>> import os
>>> os.rename(‘f1.txt’, ‘f2.txt’)
CHECK EXISTENCE OF A FILE

To avoid getting an error, it is better to check the existence of the file before
we try to delete it. We can easily do it by the help of os.path.exists( ).
Example:

DELETE A FILE
To delete a file, you have to import the os module, and use remove( ) functio

Example:
>>> import os
>>> os.remove('Deleteme.txt')
ABSOLUTE VERSUS RELATIVE PATH

 Path: A unique location of a file

 Absolute Path: A path related to the root directory is called


Absolute Path.

 Relative Path: A path related to the current directory is called


Relative Path.
ABSOLUTE PATH
Absolute Path of the File Relative.txt :
C:\Users\PARTHA\AppData\Local\Programs\Python
RELATIVE PATH 1

 Absolute Path of the File Relative1.txt :


C:\Users\PARTHA\AppData\Local\Programs\Python\Python36\progs\
Text\XII
 Current Working Directory:

C:\Users\PARTHA\AppData\Local\Programs\Python\Python36\progs
RELATIVE PATH 2
 Absolute Path of the File Relative.txt :
C:\Users\PARTHA\AppData\Local\Programs\Python
 Current Working Directory:

C:\Users\PARTHA\AppData\Local\Programs\Python\Python36\progs
FILE ATTRIBUTES

Attribute Description

name Returns the name of the file (Including path)


mode Returns mode of the file. (r or w etc.)
closed Returns True if the file closed else returns False
TELL METHOD
 It returns the current position of cursor in the file.
SEEK METHOD

 Change the cursor position by bytes as specified.


 seek() method has two formats

1) Absolute movement:
fl.seek(n) – to take the file pointer to nth character in the file
2) Relative movement:
fl.seek(n,r) – to take file pointer to nth character with respect to r position. r
has three possible values
0 -- start of stream (the default); offset should be zero or positive
1 -- current stream position; offset may be
negative (Works for binary files only)
2 -- end of stream; offset is usually negative (Works for binary files only)
SEEK METHOD: ABSOLUTE MOVEMENT

You might also like