Chapter 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

Chapter 5

File operation
Declaration
 These slides are made for UIT, BU students only. I am not
holding any copy write of it as I had collected these study
materials from different books and websites etc. I have not
mentioned those to avoid complexity.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.2


Topics
 Different mode of file access
 Different I/O methods for file

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.3


File and File handling
 A file contains a collection of data and information. Data can be
updated or shared through files.
 File handing in Python performs function such as creating,
reading, updating, deleting files.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.4


File Handling in Python
 Python supports file handling and allows users to handle files
i.e., to read and write files, along with many other file handling
options, to operate on files.
 Python treats files differently as text or binary.
 Text files: In this type of file, each line of text is terminated with
a special character called EOL (End of Line), which is the new
line character (‘\n’) in Python by default. In the case of
CSV(Comma Separated Values) files, the EOF is a comma by
default.
 Binary files: In this type of file, there is no terminator for a line,
and the data is stored after converting it into machine-
understandable binary language, i.e., 0 and 1 format.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.5


File Handling in Python
 Python distinguishes between text and binary modes when
working with files to handle character encoding, end-of-line
conversions, and data types differently. Choosing the
appropriate mode depends on the nature of the data in the file
you are reading or writing. Text mode is suitable for text files
with character data, while binary mode is used for files
containing non-textual data, such as images, audio, or any
binary file format.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.6


File Operation in Python
In Python file operation take place in the following order
1. Open a file
2. Read and write (perform operation)
3. Close the file.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.7


File Handling

 Opening a file refers to getting the file ready either for reading or for
writing.
 This can be done using the open() function.
 This function returns a file object and takes two arguments, one
that accepts the file name and another that accepts the
mode(Access Mode).
 Now, the question arises what is the access mode? Access modes
govern the type of operations possible in the opened file. It refers to
how the file will be used once it’s opened.
 These modes also define the location of the File Handle in the
file. File handle is like a cursor, which defines from where the data
has to be read or written in the file.
 There are 6 access modes in python.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.8


open() function
 Before performing any operation on the file like reading or
writing, first, we have to open that file.
 For this, we should use Python’s inbuilt function open() but at
the time of opening, we have to specify the mode, which
represents the purpose of the opening file.
f = open(filename, mode)

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.9


Mode

 Read Only (‘r’): Open text file for reading. The handle is
positioned at the beginning of the file. If the file does not exist,
raises an I/O error. This is also the default mode in which the file
is opened.
 Read and Write (‘r+’): Open the file for reading and writing. The
handle is positioned at the beginning of the file. Raises I/O error
if the file does not exist.
 Write Only (‘w’): Open the file for writing. For the existing files,
the data is truncated and over-written. The handle is positioned
at the beginning of the file. Creates the file if the file does not
exist.
 Write and Read (‘w+’): Open the file for reading and writing. For
existing files, data is truncated and over-written. The handle is
positioned at the beginning of the file.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.10


Mode

 Append Only (‘a’): Open the file for writing. The file is created if
it does not exist. The handle is positioned at the end of the file.
The data being written will be inserted at the end, after the
existing data.
 Append and Read (‘a+’): Open the file for reading and writing.
The file is created if it does not exist. The handle is positioned at
the end of the file. The data being written will be inserted at the
end, after the existing data.
 Read Only in Binary format(‘rb’): It lets the user open the file
for reading in binary format.
 Read and Write in Binary Format(‘rb+’): It lets the user open
the file for reading and writing in binary format.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.11


Mode

 Write Only in Binary Format(‘wb’): It lets the user open the file
for writing in binary format. When a file gets opened in this mode,
there are two things that can happen mostly. A new file gets
created if the file does not exist. The content within the file will
get overwritten if the file exists and has some data stored in it.
 Write and Read in Binary Format(‘wb+’): It lets the user open
the file for reading as well as writing in binary format. When a file
gets opened in this mode, there are two things that can mostly
happen. A new file gets created for writing and reading if the file
does not exist. The content within the file will get overwritten if
the file exists and has some data stored in it.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.12


Mode

 Append only in Binary Format(‘ab’): It lets the user open the


file for appending in binary format. A new file gets created if there
is no file. The data will be inserted at the end if the file exists and
has some data stored in it.
 Append and Read in Binary Format(‘ab+’): It lets the user
open the file for appending and reading in binary format. A new
file will be created for reading and appending if the file does not
exist. We can read and append if the file exists and has some
data stored in it.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.13


open() function

 File_object = open(r"File_Name", "Access_Mode")


 The r is placed before filename to prevent the characters in
filename string to be treated as special character. For example, if
there is \temp in the file address, then \t is treated as the tab
character and error is raised of invalid address. The r makes the
string raw, that is, it tells that the string is without any special
characters. The r can be ignored if the file is in same directory
and address is not being placed.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.14


open() function
# Open function to open the file "MyFile1.txt"
# (same directory) in read mode and
file1 = open("MyFile1.txt", "r")

# store its reference in the variable file1


# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt", "r+")
 Here, file1 is created as object for MyFile1 and file2 as object for
MyFile2.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.15


open() function
# a file named “UIT", will be opened with the reading mode.
file = open(‘UIT.txt', 'r') or open(‘UIT.txt', 'rt') # t for text mode
# This will print every line one by one in the file
for each in file:
print (each)

 The open command will open the file in the read mode and the
for loop will print each line present in the file.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.16


open() function
 There is more than one way to read a file in Python. If you need
to extract a string that contains all characters in the file then we
can use file.read(). The full code would work like this:

# Python code to illustrate read() mode


file = open("file.txt", "r")
print (file.read())

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.17


open() function
 Another way to read a file is to call a certain number of
characters like in the following code the interpreter will read the
first five characters of stored data and return it as a string:
# Python code to illustrate read() mode character wise
file = open("file.txt", "r")
print (file.read(5))

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.18


close() function
In Python, file.close() is a method used to manually close a file that
has been opened using the open() function. When you open a file
for reading or writing using open(), it's a good practice to close the
file explicitly using file.close() when you're done working with it.

# Python code to create a file


file = open(‘UIT.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.19


close() function
The file.close() method serves a few important purposes:
 Resource Cleanup: It releases the system resources (like memory)
associated with the open file. This is particularly important when you're
working with a large number of files or when working in an environment
with limited resources.
 Flushes Data: Any data that has been buffered (in memory) but not yet
written to the file will be flushed (written) to the file before it's closed.
This ensures that all changes made to the file are saved.
 Prevents Further Access: After closing a file, you can no longer read
from or write to it using the same file object. It prevents accidental
modifications after you consider the file operation as complete.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.20


append() mode
# Python code to illustrate append() mode
file = open(‘UIT.txt','a')
file.write("This will add this line")
file.close()

 In Python, the append() mode ("a") is used when opening a file


to write data to it while preserving the existing content of the file.
 The "a" mode is commonly used when you want to add data to a
log file, maintain a history of changes, or continuously update a
file with new information without removing the old content.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.21


with() function
# Python code to illustrate with()
with open("file.txt") as file:
data = file.read()
# do something with data

It is a way to open and read a file in Python using a context manager.


 open("file.txt"): This line opens the file named "file.txt" in the current
working directory in the default read mode ("r"). It creates a file object
that can be used to interact with the file.
 with open("file.txt") as file: This line starts a context using a with
statement. The with statement is used to ensure that the file is properly
closed after it's read. It's a good practice because it automatically takes
care of closing the file, even if an exception is raised within the block.
 data = file.read(): Within the context, this line reads the entire content of
the file and stores it in the data variable as a string. After this line, you
can work with the contents of the file, and the file is automatically closed
when you exit the with block.
9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.22
with() function
# Python code to illustrate with() alongwith write()
with open("file.txt", "w") as f:
f.write("Hello World!!!")

 open("file.txt", "w"): This line opens the file "file.txt" in write mode ("w"). If
the file doesn't exist, it will be created. If it does exist, its previous
content will be completely overwritten.
 with open("file.txt", "w") as f:: This line starts a context using a with
statement. It ensures that the file is properly closed after writing. This is
important because it not only saves your changes but also releases the
system resources associated with the file.
 f.write("Hello World!!!"): Within the context, this line writes the string
"Hello World!!!" to the file. After executing this line, the file will contain
only the text "Hello World!!!".

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.23


split() function
 We can also split lines using file handling in Python. This splits
the variable when space is encountered. You can also split using
any characters as we wish.
# Python code to illustrate split() function
with open("file.text", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)
 Assuming you have a file named "file.txt" with lines of text, this
code will read each line, split it into words (based on
whitespace), and print the list of words for each line.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.24


Reading from a file
 read() : Returns the read bytes in form of a string. Reads n
bytes, if no n specified, reads the entire file.
File_object.read([n])
 readline() : Reads a line of the file and returns in form of a
string. For specified n, reads at most n bytes. However, does not
reads more than one line, even if n exceeds the length of the
line.
File_object.readline([n])
 readlines() : Reads all the lines and return them as each line a
string element in a list.
File_object.readlines()
‘\n’ is treated as a special character of two bytes.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.25


Reading from a file
# Program to show various ways to
# read data from a file.

# Creating a file
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# Writing data to a file


file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.26


Reading from a file
file1 = open("myfile.txt", "r+")
print("Output of Read function is ")
print(file1.read())
print()

# seek(n) takes the file handle to the nth


# bite from the beginning.
file1.seek(0)

print("Output of Readline function is ")


print(file1.readline())
print()

file1.seek(0)

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.27


Reading from a file
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()

file1.seek(0)

print("Output of Readline(9) function is ")


print(file1.readline(9))
print()

file1.seek(0)

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.28


Reading from a file
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.29


Reading from a file
 Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London

Output of Readline function is


Hello

Output of Read(9) function is


Hello
Th

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.30


Reading from a file
Output of Readline(9) function is
Hello

Output of Readlines function is


['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.31


With statement
 with statement in Python is used in exception handling to make
the code cleaner and much more readable. It simplifies the
management of common resources like file streams. Unlike the
above implementations, there is no need to call file.close() when
using with statement. The with statement itself ensures proper
acquisition and release of resources.
with open filename as file:

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.32


With statement
# Program to show various ways to
# read data from a file.

L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# Creating a file
with open("myfile.txt", "w") as file1:
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes

with open("myfile.txt", "r+") as file1:


# Reading form a file
print(file1.read())
9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.33
With statement
 Output:
Hello
This is Delhi
This is Paris
This is London

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.34


Writing to file
# Open function to open the file "MyFile1.txt"
# (same directory) in read mode and
file1 = open("MyFile.txt", "w")

# store its reference in the variable file1


# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt", "w+")

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.35


Writing to file
 There are two ways to write in a file.
 write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
 writelines() : For a list of string elements, each string is inserted
in the text file. Used to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
 Note: ‘\n’ is treated as a special character of two bytes.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.36


Writing to file
# Python program to demonstrate
# writing to file

# Opening a file
file1 = open('myfile.txt', 'w')
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
s = "Hello\n"

# Writing a string to file


file1.write(s)

# Writing multiple strings


# at a time
file1.writelines(L)
9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.37
Writing to file
# Closing file
file1.close()

# Checking if the data is


# written to file or not
file1 = open('myfile.txt', 'r')
print(file1.read())
file1.close()

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.38


Writing to file
 Output:
Hello
This is Delhi
This is Paris
This is London

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.39


Appending to a file
 When the file is opened in append mode, the handle is
positioned at the end of the file. The data being written will be
inserted at the end, after the existing data. Let’s see the below
example to clarify the difference between write mode and
append mode.

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.40


Appending to a file
# Python program to illustrate
# Append vs write mode
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
file1.writelines(L)
file1.close()

# Append-adds at last
file1 = open("myfile.txt", "a") # append mode
file1.write("Today \n")
file1.close()

file1 = open("myfile.txt", "r")


print("Output of Readlines after appending")

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.41


Appending to a file
print(file1.read())
print()
file1.close()

# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()

file1 = open("myfile.txt", "r")


print("Output of Readlines after writing")
print(file1.read())
print()
file1.close()
9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.42
Appending to a file
 Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
Today

Output of Readlines after writing


Tomorrow

9/13/2023 7:56 PM Dr. Dipankar Dutta, UIT, BU 1.43


End of Chapter 5

Questions?

You might also like