Python Notes - 4 Unit - 240610 - 164821
Python Notes - 4 Unit - 240610 - 164821
File handling in Python is a powerful and versatile tool that can be used to perform a wide
range of operations. 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 and this is important. Each line of code includes
a sequence of characters, and they form a text file. Each line of a file is terminated with a
special character, called the EOL or End of Line characters like comma {,} or newline
character. It ends the current line and tells the interpreter a new one has begun.
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.
In Python, files are treated in two modes as text or binary. The file may be in the text or binary
format, and each line of a file is ended with the special character like a comma (,) or a newline
character. Python executes the code line by line.
Flexibility: File handling in Python is highly flexible, as it allows you to work with
different file types (e.g. text files, binary files, CSV files, etc.), and to perform
different operations on files (e.g. read, write, append, etc.).
Security risks: File handling in Python can also pose security risks, especially if the
program accepts user input that can be used to access or modify sensitive files on the
system.
Complexity: File handling in Python can be complex, especially when working with
more advanced file formats or operations. Careful attention must be paid to the code
to ensure that files are handled properly and securely.
Python provides built-in functions for creating, writing, and reading files. Two types of files
can be handled in Python, normal text files and binary files (written in binary language, 0s,
and 1s).
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.
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.
Access modes govern the type of operations possible in the opened file. It refers to how the
file will be used once its opened. These modes also define the location of the File Handle in
the file. The file handle is like a cursor, which defines from where the data has to be read or
written in the file and we can get Python output in text file. There are 6 access modes in
Python.
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 an existing file,
data is truncated and over-written. The handle is positioned at the beginning of the
file.
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 binary (‘rb’): Opens a file for reading only in binary format. The file
pointer is placed at the beginning of the file. This is the default mode.
Read and Write only binary (‘rb+’): Opens a file for both reading and writing in
binary format. The file pointer placed at the beginning of the file.
Opens binary mode only (‘b’): Opens the file in binary mode
Opens text mode only (‘t’): Opens the file in text mode (default)
Open file for updating [reading and writing] (‘+’): open file for updating (reading
and writing).
Write only binary (‘wb’): Opens a file for writing only in binary format. Overwrites
the file if the file exists. If the file does not exist, creates a new file for writing.
Write and Read only binary (‘wb+’): Opens a file for both writing and reading in
binary format. Overwrites the existing file if the file exists. If the file does not exist,
creates a new file for reading and writing.
Append only binary (‘ab’): Opens a file for appending in binary format. 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.
Append and Read binary (‘ab+’): Opens a file for both appending and reading in
binary format. 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 reading and
writing.
Opens for exclusive creation only (‘x’): open for exclusive creation, failing if the
file already exists.
There are two kinds of memory in a computer i.e. Primary and Secondary memory every file
that you saved or anyone saved is on secondary memory cause any data in primary memory is
deleted when the computer is powered off. So, when you need to change any text file or just to
work with them in python you need to load that file into primary memory.
Python interacts with files loaded in primary memory or main memory through “file
handlers” (This is how your operating system gives access to python to interact with the file
you opened by searching the file in its memory if found it returns a file handler and then you
can work with the file ).
It is done using the open() function. No module is required to be imported for this function.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, the full address of
the file should be written in place of the filename.
Note: The r is placed before the filename to prevent the characters in the filename string to
be treated as special characters.
For example, if there is \temp in the file address, then \t is treated as the tab character, and an
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 the same directory and the
address is not being placed.
Example:
# Open function to open the file "MyFile1.txt"
# (same directory) in append mode and
file1 = open("MyFile1.txt","a")
Here, file1 is created as an object for MyFile1 and file2 as object for MyFile2
close() function closes the file and frees the memory space acquired by that file. It is used at
the time when the file is no longer needed or if it is to be opened in a different file mode.
File_object.close()
Example:
# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt","a")
file1.close()
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.
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()
Note: ‘\n’ is treated as a special character of two bytes.
In this example, a file named “myfile.txt” is created and opened in write mode ("w"). Data is
written to the file using write and writelines methods. The file is then reopened in read and
append mode ("r+"). Various read operations, including read, readline, readlines, and the use
of seek, demonstrate different ways to retrieve data from the file. Finally, the file is closed.
Example:
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Patna \n", "This is Lucknow \n"]
file1.seek(0)
file1.seek(0)
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Patna
This is Lucknow
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Patna \n', 'This is Lucknow \n']
In this example, a file named “myfile.txt” is initially opened in write mode ("w") to write
lines of text. The file is then reopened in append mode ("a"), and “Today” is added to the
existing content. The output after appending is displayed using readlines. Subsequently, the
file is reopened in write mode, overwriting the content with “Tomorrow”. The final output
after writing is displayed using readlines.
Example:
# Python program to illustrate
# Append vs write mode
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Patna\n","This is Lucknow\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")
print(file1.readlines())
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.readlines())
print()
file1.close()
Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Patna \n', 'This is Lucknow \n', 'Today \n']
Output of Readlines after writing
['Tomorrow \n']
File Objects
A file object allows us to use, access and manipulate all the user accessible files. One can
read and write any such files.
open(file_address, access_mode)
Examples of accessing a file: A file can be opened with a built-in function called
open(). This function takes in the file’s address and the access_mode and returns a file
object.
read([size]): It reads the entire file and returns it contents in the form of a string.
Reads at most size bytes from the file (less if the read hits EOF before obtaining size
bytes). If the size argument is negative or omitted, read all data until EOF is reached.
Example:
# Reading a file
f = open(__file__, 'r')
#read()
text = f.read(10)
print(text)
f.close()
readline([size]): It reads the first line of the file i.e till a newline character or an EOF
in case of a file having a single line and returns a string. If the size argument is present
and non-negative, it is a maximum byte count (including the trailing newline) and an
incomplete line may be returned. An empty string is returned only when EOF is
encountered immediately.
Example:
# Reading a line in a file
f = open(__file__, 'r')
#readline()
text = f.readline(20)
print(text)
f.close()
readlines([sizehint]): It reads the entire file line by line and updates each line to a list
which is returned.Read until EOF using readline() and return a list containing the lines
thus read. If the optional sizehint argument is present, instead of reading up to EOF,
whole lines totalling approximately sizehint bytes (possibly after rounding up to an
internal buffer size) are read.
Example:
# Reading a file
f = open(__file__, 'r')
#readline()
text = f.readlines(25)
print(text)
f.close()
write(string): It writes the contents of string to the file. It has no return value. Due to
buffering, the string may not actually show up in the file until the flush() or close()
method is called.
Example:
# Writing a file
f = open(__file__, 'w')
line = 'Welcome Gitms\n'
#write()
f.write(line)
f.close()
Example:
# Reading and Writing a file
f = open(__file__, 'r+')
lines = f.read()
f.write(lines)
f.close()
Example:
# Writing and Reading a file
f = open(__file__, 'w+')
lines = f.read()
f.write(lines)
f.close()
Example:
# Appending a file
f = open(__file__, 'a')
lines = 'Welcome Goels\n'
f.write(lines)
f.close()
Example:
# Appending and reading a file
f = open(__file__, 'a+')
lines = f.read()
f.write(lines)
f.close()
Example:
# Writing a file
f = open(__file__, 'a+')
lines = f.readlines()
#writelines()
f.writelines(lines)
f.close()
tell(): It returns an integer that tells us the file object’s position from the beginning of
the file in the form of bytes
Example:
# Telling the file object position
f = open(__file__, 'r')
lines = f.read(10)
#tell()
print(f.tell())
f.close()
Example:
# Setting the file object position
f = open(__file__, 'r')
lines = f.read(10)
print(lines)
#seek()
print(f.seek(2,2))
lines = f.read(10)
print(lines)
f.close()
flush(): Flush the internal buffer, like stdio‘s fflush(). It has no return value. close()
automatically flushes the data but if you want to flush the data before closing the file
then you can use this method.
Example:
# Clearing the internal buffer before closing the file
f = open(__file__, 'r')
lines = f.read(10)
#flush()
f.flush()
print(f.read())
f.close()
fileno(): Returns the integer file descriptor that is used by the underlying
implementation to request I/O operations from the operating system.
Example:
# Getting the integer file descriptor
f = open(__file__, 'r')
#fileno()
print(f.fileno())
f.close()
isatty(): Returns True if the file is connected to a tty(-like) device and False if not.
Example:
# Checks if file is connected to a tty(-like) device
f = open(__file__, 'r')
#isatty()
print(f.isatty())
f.close()
next(): It is used when a file is used as an iterator. The method is called repeatedly.
This method returns the next input line or raises StopIteration at EOF when the file is
open for reading( behaviour is undefined when opened for writing).
Example:
# Iterates over the file
f = open(__file__, 'r')
#next()
try:
while f.next():
print(f.next())
except:
f.close()
truncate([size]): Truncate the file’s size. If the optional size argument is present, the
file is truncated to (at most) that size. The size defaults to the current position. The
current file position is not changed.
Note that if a specified size exceeds the file’s current size, the result is platform-
dependent: possibilities include that the file may remain unchanged, increase to the
specified size as if zero-filled, or increase to the specified size with undefined new
content.
Example:
# Truncates the file
f = open(__file__, 'w')
#truncate()
f.truncate(10)
f.close()
close(): Used to close an open file. A closed file cannot be read or written any more.
Example:
# Opening and closing a file
f = open(__file__, 'r')
#close()
f.close()
Attributes:
closed: returns a boolean indicating the current state of the file object. It returns true if
the file is closed and false when the file is open.
encoding: The encoding that this file uses. When Unicode strings are written to a file,
they will be converted to byte strings using this encoding.
mode: The I/O mode for the file. If the file was created using the open() built-in
function, this will be the value of the mode parameter.
name: If the file object was created using open(), the name of the file.
newlines: A file object that has been opened in universal newline mode have this
attribute which reflects the newline convention used in the file. The value for this
attribute are “\r”, “\n”, “\r\n”, None or a tuple containing all the newline types seen.
softspace: It is a boolean that indicates whether a space character needs to be printed
before another value when using the print statement.
Example:
f = open(__file__, 'a+')
print(f.closed)
print(f.encoding)
print(f.mode)
print(f.newlines)
print(f.softspace)
The seek function is a built-in function in Python that is used to set the current position of the
file pointer within a file. The file pointer is a marker that indicates the current position in the
file, and it is used to read or write data from that point. This function is particularly useful
when reading or writing large files, as it allows us to move the file pointer to a specific
location within the file and read or write data from that point.
file.seek(offset, whence)
Here, file is the file object that we want to set the position of the file pointer in.
The first argument, offset, is the number of bytes we want to move the file pointer. The
second argument, whence, specifies the reference position from where we want to move the
file pointer. The possible values of whence are
An example of how to use the seek function to set the position of the file pointer within a file.
data.txt File:
Example:
# Open a file in read mode
file = open("data.txt", "r")
# Set the position of the file pointer to byte 10
file.seek(10)
# Read the next 5 bytes from the file
data = file.read(5)
# Print the data that was read
print(data)
# Close the file
file.close()
Output:
is an
Explanation:
In this example, we opened a file called data.txt in read mode and set the position of the file
pointer to byte 10 using the seek function. We then read the next 5 bytes from the file using
the read function and printed the data that was read which gives us an output as “is an”.
Finally, we closed the file using the close function.
Different Modes of the Seek Function in Python
The seek function can be used in three different modes: absolute mode, relative mode, and
from end mode.
Absolute Mode
In absolute mode, the offset parameter specifies the number of bytes from the start of the file
where we want to set the file pointer. In other words, the file pointer is set to an absolute
position within the file.
The syntax for using the seek function in python in absolute mode is as follows:
file.seek(offset, 0)
Here, the second parameter is 0, which specifies that we want to set the file pointer in
absolute mode.
data.txt File:
Example:
# Open a file in read mode
file = open("data.txt", "r")
# Set the position of the file pointer to byte 10
file.seek(10, 0)
# Read the next 5 bytes from the file
data = file.read(5)
# Print the data that was read
print(data)
# Close the file
file.close()
Output:
is an
Relative Mode
In relative mode, the offset parameter specifies the number of bytes to move the file pointer
from its current position. In other words, the file pointer is set to a position relative to its
current position.
The syntax for using the seek function in relative mode is as follows:
file.seek(offset, 1)
Here, the second parameter is 1, which specifies that we want to set the file pointer in relative
mode.
data.txt File:
Example:
# Open a file in read mode
file = open("data.txt", "r")
# Set the position of the file pointer to 10 bytes from the current position
file.seek(10, 1)
# Read the next 5 bytes from the file
data = file.read(5)
# Print the data that was read
print(data)
# Close the file
file.close()
Output:
is an
Explanation:
In this example, we opened a file called data.txt in read mode and set the position of the file
pointer to 10 bytes from its current position using the seek function in relative mode. We then
read the next 5 bytes from the file using the read function and printed the data that was read.
Finally, we closed the file using the close function.
In from end mode, the offset parameter specifies the number of bytes from the end of the file
where we want to set the file pointer. In other words, the file pointer is set to a position
relative to the end of the file.
The syntax for using the seek function in from end mode is as follows:
file.seek(offset, 2)
Here, the second parameter is 2, which specifies that we want to set the file pointer in from
end mode.
data.txt File:
Output:
h Ins
Explanation:
In this example, we opened a file called data.txt in read mode and set the position of the file
pointer to 10 bytes from the end of the file using the seek function in from end mode. We
then read the next 5 bytes from the file using the read function and printed the data that was
read. Finally, we closed the file using the close function.
The tell function is another built-in function in Python that is used to get the current position
of the file pointer within a file.
file.tell()
Here, file is the file object for which we want to get the current position of the file pointer.
data.txt File:
Example:
# Open a file in read mode
file = open("data.txt", "r")
# Get the current position of the file pointer
position = file.tell()
# Print the current position of the file pointer
print(position)
# Close the file
file.close()
Output:
0
Explanation:
In this example, we opened a file called data.txt in read mode and used the tell function to get
the current position of the file pointer. We then printed the current position of the file pointer
which shows “0” on the console and closed the file using the close function.