0% found this document useful (0 votes)
11 views

UNIT 4 Python

Uploaded by

papakhanna78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

UNIT 4 Python

Uploaded by

papakhanna78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

UNIT – 4

File Operations in Python

Ankita Sharma CSE unit 4 1


File Handling

• The file handling plays an important role when the data needs to
be stored permanently into the file.

• A file is a named location on disk to store related information.


We can access the stored information (non-volatile) after the
program termination.

• The types of activities that you can perform on the opened file
are controlled by Access Modes.
Ankita Sharma CSE unit 4 2
Types of Files in Python In Python, there are two types of files. They are:
● Text files
● Binary files
Text files store the data in the form of characters. For example, if we store
the employer name "Ganesh", it will be stored as 6 characters and the
employee salary 8900.75 is stored as 7 characters. Normally, text files are
used to store characters or strings. (EG;.txt,.csv,.pdf)
Binary files store entire data in the form of bytes, i.e. a group of 8 bits
each. For example a character is stored as a byte and an integer is stored
in the form of 8 bytes (on a 64 bit machine). When the data is retrieved
from the binary file, the programmer can retrieve the data as bytes.
Binary files can be used to store images, audio and video

Ankita Sharma CSE unit 4 3


How to Create Files in Python
• It is very important to know how to create files, store data in the files and
retrieve the data from the files in Python. To do any operation on files, first
of all we should open the files.
file handler = open("path/file name", "open mode", "buffering")
• A buffer represents a temporary block of memory. 'buffering' is an optional
integer used to set the size of the buffer for the file. In the binary mode, we
can pass 0 as a buffering integer to inform us not to use any buffering. In
text mode, we can use 1 for buffering to retrieve data from the file one line
at a time. Apart from these, we can use any positive integer for buffering.

In Python, you use the open() function with one of the following options –
"x" or "w" – to create a new file:

Ankita Sharma CSE unit 4 4


• "x" – Create: this command will create a new file if and only if there
is no file already in existence with that name

or else it will return an error.

Ankita Sharma CSE unit 4 5


• "w" – Write: this command will create a new text file whether or not
there is a file in the memory with the new specified name. It does not
return an error if it finds an existing file with the same name – instead
it will overwrite the existing file.

Ankita Sharma CSE unit 4 6


Closing a File
• A file which is opened should be closed using the close() method.
• Once a file is opened but not closed, then the data of the file may be
corrupted or deleted in some cases.
• Also, if the file is not closed, the memory utilized by the file is not
freed, leading to problems like insufficient memory. This happens
when we are working with several files simultaneously. Hence it is
mandatory to close the file

f.close()
Ankita Sharma CSE unit 4 7
File Access Modes

Ankita Sharma CSE unit 4 8


Ankita Sharma CSE unit 4 9
Ankita Sharma CSE unit 4 10
How to Write to a File in Python
• There are two methods of writing to a file in Python, which are:

The write() method:

This function inserts the string into the text file on a single line.
f.write(str) In this way, write() can be used to store a character or a
group of characters (string) into a file represented by the file object ‘f’.

Ankita Sharma CSE unit 4 11


• Based on the file we have created above, the below line of code will
insert the string into the created text file, which is "myfile.txt.”

Ankita Sharma CSE unit 4 12


• In this way, write() can be used to store a character or a group of
characters (string) into a file represented by the file object ‘f’.
• A Python program to create a text file to store individual characters.

Ankita Sharma CSE unit 4 13


• If we run this program again, the already entered data in the file is
lost and the file will be created as a fresh file without any data. In this
way, new data entered by us will only be stored into the file and the
previous data is lost.
• If we want to retain the previous data and want to add the new data
at the end of the file, then we have to open the file in append mode
as: f = open('myfile1.txt', 'a')

Ankita Sharma CSE unit 4 14


• The writelines() method:
This function inserts multiple strings at the same time. A list of string
elements is created, and each string is then added to the text file.

Ankita Sharma CSE unit 4 15


Read File in Python
• All methods for reading a text file such as read(), readline(), and
readlines().
Steps for Reading a File in Python
1. Find the path of a file
We can read a file using both relative path and absolute path. The path
is the location of the file on the disk.
An absolute path contains the complete directory list required to
locate the file.
A relative path contains the current directory and then the file name.

Ankita Sharma CSE unit 4 16


2. Open file in Read Mode

f= open(r'File_Path', 'r‘)

3. Read content from a file.

Once opened, we can read all the text or content of the file using the
read() method. You can also use the readline() to read file line by line or
the readlines() to read all lines.
For example, content = f.read()

Ankita Sharma CSE unit 4 17


4. Close file after completing the read operation
We need to make sure that the file will be closed properly after
completing the file operation. Use f.close() to close a file.

Ankita Sharma CSE unit 4 18


• The next step is to read the data from 'myfile1.txt' and display it on
the monitor.
• To read data from a text file, we can use read() method

Ankita Sharma CSE unit 4 19


When Path is given instead of
file name in open function

Ankita Sharma CSE unit 4 20


Ankita Sharma CSE unit 4 21
Reading a File Using the with Statement
with open(__file__, accessmode) as f:

• main advantages of opening a file using ‘with’ statement


• The with statement simplifies exception handling by encapsulating
common preparation and cleanup tasks.
• This also ensures that a file is automatically closed after leaving the
block.
• As the file is closed automatically it ensures that all the resources that
are tied up with the file are released.

Ankita Sharma CSE unit 4 22


Ankita Sharma CSE unit 4 23
Ankita Sharma CSE unit 4 24
readline(): Read a File Line by Line
• Using the readline() method, we can read a file line by line. by default,
this method reads the first line in the file.

Ankita Sharma CSE unit 4 25


Reading First N lines From a File Using readline()

• We can read the first few set of lines from a file by using the
readline() method. Run a loop fo n times using for loop and range()
function, and use the readline() method in the loop’s body.

• Example next page 

Ankita Sharma CSE unit 4 26


Ankita Sharma CSE unit 4 27
Reading Entire File Using readline()
• We can use the readline() method to read the entire file using the
while loop.
• We need to check whether the pointer has reached the End of the
File and then loop through the file line by line

Ankita Sharma CSE unit 4 28


Code explaination :--

• while line != '':


This loop will continue running until the end of the file (EOF) is
reached.When readline() encounters the EOF, it returns an empty string (''),
causing the loop to stop.

• print(line, end='')This prints the current line to the console.The end=''


argument ensures that Python does not add an extra newline (since
readline() already includes it).

• line = fp.readline()This reads the next line from the file and updates the
variable line.The loop will continue processing lines until there are no
more lines to read
Ankita Sharma CSE unit 4 29
Reading First and the Last line using readline() :
We can get the first line by just calling the readline() method as
this method starts reading from the beginning always and we can
use the for loop to get the last line.

Ankita Sharma CSE unit 4 30


readlines(): Reading File into List
we can achieve the same using the readlines() method. This method
read file line by line into a list.

This method will return the entire file contents. The reading of the
contents will start from the beginning of the file till it reaches the EOF
(End of File).

This method will internally call the readline() method and store the
contents in a list. The output of this method is a list.

Ankita Sharma CSE unit 4 31


Ankita Sharma CSE unit 4 32
Reading first N lines from a file

Ankita Sharma CSE unit 4 33


Manipulating file pointer using seek programming :
A file pointer stores the current position of a read or write within a
file.
Python provides methods and functions to handle files. Handling
files includes operations like opening a file, after that reading the
content, adding or overwriting the content and then finally closing
the file.

By using the read() function we can read the content of the file.
What if we want to read the file from a specific position or find out
from where the reading begins? Python’s seek() and tell() functions
come in handy here.
Ankita Sharma CSE unit 4 34
• A file handle or pointer denotes the position from which the file
contents will be read or written. File handle is also called as file pointer
or cursor.
• For example, when you open a file in write mode, the file pointer is
placed at the 0th position, i.e., at the start of the file. However, it
changes (increments) its position as you started writing content into it.

• Or, when you read a file line by line, the file pointer moves one line at
a time.

• Sometimes we may have to read only a specific portion of the file, in


such cases use the seek() method to move the file pointer to that
position.

Ankita Sharma CSE unit 4 35


How to Use seek() Method
• The seek() method sets the file’s current position, and then we
can read or write to the file from that position.

• How many points the pointer will move is computed from adding
offset to a reference point; the reference point is given by the
whence argument

Ankita Sharma CSE unit 4 36


The allowed values for the whence argument are: –

• A whence value of 0 means from the beginning of the file.


• A whence value of 1 uses the current file position
• A whence value of 2 uses the end of the file as the reference
point.

The default value for the whence is the beginning of the file, which
is 0

Ankita Sharma CSE unit 4 37


Ankita Sharma CSE unit 4 38
We will use this text file to see example codes :

Ankita Sharma CSE unit 4 39


Examples :
• we will start reading the file directly from the 6th character.

Ankita Sharma CSE unit 4 40


• After adding content, we wanted to move the pointer to the beginning of
the file to read the entire file.

Ankita Sharma CSE unit 4 41


Example :

Ankita Sharma CSE unit 4 42


Seeking The End of File

Ankita Sharma CSE unit 4 43


Seek From The Current Position
• Example: Move the file handle 10 points ahead from current position

Note:

Open file in binary mode. For reading use the rb, for writing use the
wb, and for both reading and writing use rb+.
Convert byte to string if you are reading a text file.

Ankita Sharma CSE unit 4 44


Ankita Sharma CSE unit 4 45
Explaination
:

Ankita Sharma CSE unit 4 46


Ankita Sharma CSE unit 4 47
Seek backward With Negative Offset
• In some cases, we have to read characters from the end of the file. to
do that, we need to move the file pointer in a reverse direction.

• For example, move to the 10th character from the end of the file. This
can be done by setting the offset corresponding to the end of the file.

Ankita Sharma CSE unit 4 48


Ankita Sharma CSE unit 4 49
Example : Let’s suppose we have to read a file named
“myfile1.txt”.from 20th position. And also print current position

f = open(“myfile1.txt", "r")
# Second parameter is by default 0
# sets Reference point to twentieth
# index position from the beginning
f.seek(20)
# prints current position
print(f.tell())
print(f.readline())
f.close() Ankita Sharma CSE unit 4 50
Example 2: Seek() function with negative offset only works when
file is opened in binary mode. Let’s suppose the binary file contains
the following text.

Solution :

Ankita Sharma CSE unit 4 51


tell() Function To Get File Handle Position
• We can get the file handle current position using the tell()
method.
Syntax:
file_object.tell()

• There are no arguments for this method. The return value is the
integer representing the file handle position.

Ankita Sharma CSE unit 4 52


with open(r'E:\demos\files_demos\test.txt', "r+") as fp:
# Moving the file handle to the end of the file
fp.seek(0, 2)
# getting the file handle position
print('file handle at:', fp.tell())
# writing new content
fp.write("\nDemonstrating tell")
# getting the file handle position
print('file handle at:', fp.tell())
# move to the beginning
fp.seek(0)
Ankita Sharma CSE unit 4 53
# getting the file handle position
print('file handle at:', fp.tell())
# read entire file
print('***Printing File Content***')
print(fp.read())
print('***Done***')
# getting the file handle position
print('file handle at:', fp.tell())

Ankita Sharma CSE unit 4 54

You might also like