Unit -4
Python File Handling
File handling in Python is a powerful and versatile tool that can be used to perform a wide range of
operations. However, it is important to carefully consider the advantages and disadvantages of file
handling when writing Python programs, to ensure that the code is secure, reliable, and performs well.
Python File Handling
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. The concept of file handling has stretched over various
other languages, but the implementation is either complicated or lengthy, like other concepts of Python,
this concept here is also easy and short.
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. Let’s start with the reading and
writing files.
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.
Python File Open
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)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data, then it will be
overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. This mode does not override the existing data, but you
can modify the data starting from the beginning of the file.
5. w+: To write and read data. It overwrites the previous file if one exists, it will truncate the file to
zero length or create a file if it does not exist.
6. a+: To append and read data from the file. It won’t override existing data.
How to read from a file in Python
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that
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 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. Different access
modes for reading a file are –
1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file.
If the file does not exists, raises I/O error. This is also the default mode in which file is opened.
2. 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 exists.
3. 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.
Closing a file
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.
Syntax:
File_object.close()
Reading from a file
There are three ways to read data from a text file.
read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the
entire file.
o 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.
o File_object.readline([n])
readlines() : Reads all the lines and return them as each line a string element in a list.
o File_object.readlines()
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.
Syntax:
with open filename as file:
Writing to file in Python
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that
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 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. Different access
modes for reading a file are –
Write Only (‘w’) : Open the file for writing. For an existing file, 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.
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.
o 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.
o File_object.writelines(L) for L = [str1, str2, str3]