0% found this document useful (0 votes)
4 views17 pages

Python Notes - 4 Unit - 240610 - 164821

The document provides an overview of file handling in Python, detailing its advantages, disadvantages, and various operations such as reading and writing to text and binary files. It explains different file access modes, how files are loaded into memory, and includes examples of using functions like open(), write(), and read(). Additionally, it highlights the importance of careful coding to avoid errors and security risks associated with file handling.

Uploaded by

akhilverma9580
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)
4 views17 pages

Python Notes - 4 Unit - 240610 - 164821

The document provides an overview of file handling in Python, detailing its advantages, disadvantages, and various operations such as reading and writing to text and binary files. It explains different file access modes, how files are loaded into memory, and includes examples of using functions like open(), write(), and read(). Additionally, it highlights the importance of careful coding to avoid errors and security risks associated with file handling.

Uploaded by

akhilverma9580
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/ 17

Python (Unit 4)

 File handling in Python

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.

 Advantages of File Handling in Python

 Versatility: File handling in Python allows you to perform a wide range of


operations, such as creating, reading, writing, appending, renaming, and deleting files.

 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.).

 User–friendly: Python provides a user-friendly interface for file handling, making it


easy to create, read, and manipulate files.

 Cross-platform: Python file-handling functions work across different platforms (e.g.


Windows, Mac, Linux), allowing for seamless integration and compatibility.

 Disadvantages of File Handling in Python

 Error-prone: File handling operations in Python can be prone to errors, especially if


the code is not carefully written or if there are issues with the file system (e.g. file
permissions, file locks, 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.

 Performance: File handling operations in Python can be slower than other


programming languages, especially when dealing with large files or performing
complex operations.

 Reading and writing to text files in Python

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.

 Python File Operations

 File Access Modes

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 only (‘r’)


 Read and Write (‘r+’)
 Write only (‘w’)
 Write and Read (‘w+’)
 Append only (‘a’)
 Append and Read (‘a+’)
 Read only binary (‘rb’)
 Read and Write only binary (‘rb+’)
 Write only binary (‘wb’)
 Write and Read only binary (‘wb+’)
 Opens binary mode only (‘b’)
 Opens text mode only (‘t’)
 Open file for updating [reading and writing] (‘+’)
 Append only binary (‘ab’)
 Append and Read binary (‘ab+’)
 Opens for exclusive creation only (‘x’)
 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 the I/O error. This is also the default mode
in which a 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 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.

 How Files are Loaded into Primary Memory

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 ).

 Opening a Text File in Python

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")

# store its reference in the variable file1


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

Here, file1 is created as an object for MyFile1 and file2 as object for MyFile2

 Closing a Text File in Python

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()

 Writing to a file in Python

There are two ways to write in a file:


 Using write()
 Using writelines()

 Writing to a Python Text File Using write()

write() : Inserts the string str1 in a single line in the text file.

File_object.write(str1)

 Writing to a Text File Using writelines()

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]

 Reading from a file in Python

There are three ways to read data from a text file:


 Using read()
 Using readline()
 Using readlines()

 Reading From a File Using read()

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])

 Reading a Text File Using readline()

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])

 Reading a File Using readlines()

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"]

# \n is placed to indicate EOL (End of Line)


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

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

print("Output of Read function is ")


print(file1.read())
print()

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


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

print("Output of Readline function is ")


print(file1.readline())
print()

file1.seek(0)

# 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))

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']

 Appending To a File in Python

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(): Opens a file in given access mode.

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()

 More Examples in different modes:

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()

 writelines(sequence): It is a sequence of strings to the file usually a list of strings or


any other iterable data type. It has no return value.

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()

 seek(offset, from_where): It is used to change the file object’s position. Offset


indicates the number of bytes to be moved. from_where indicates from where the
bytes are to be moved.

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)

 Manipulating file pointer using seek

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.

 Syntax of Seek Function in Python

The syntax of the seek function in Python is as follows:

file.seek(offset, whence)

Here, file is the file object that we want to set the position of the file pointer in.

 Parameters of Seek Function in Python

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

 0 (default): refers to the beginning of the file


 1: refers to the current position of the file pointer
 2: refers to the end of the file

Example of Seek Function in Python

An example of how to use the seek function to set the position of the file pointer within a file.

data.txt File:

GoelGitms is an Ed-Tech Institution.

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.

An example of how to use the seek function in absolute mode.

data.txt File:

GoelGitms is an Ed-Tech Institution.

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.

An example of how to use the seek function in relative mode:

data.txt File:

GoelGitms is an Ed-Tech Institution.

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.

 From End Mode

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.

An example of how to use the seek function in from end mode.

data.txt File:

GoelGitms is an Ed-Tech Institution.


Example:
# Open a file in read mode
file = open("data.txt", "r")
# Set the position of the file pointer to 10 bytes from the end of the file
file.seek(-10, 2)
# 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:

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.

 Using the Tell 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.

The syntax of the tell function is as follows:

file.tell()

Here, file is the file object for which we want to get the current position of the file pointer.

An example of how to use the tell function:

data.txt File:

GoelGitms is an Ed-Tech Institution.

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.

You might also like