File Handling

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

INTRODUCTION OF FILE HANDLING IN PYTHON

What is File Handling?


The process of file handling refers to how we store the available data or info in a file with the help of
a program.
This data can be fetched/extracted from these files to work again in any program.

What is a File ?
A file refers to a source in which a program stores the information/data in the form of bytes of
sequence on a disk (permanently).
The content available on a file isn’t volatile like the compiler memory .
But the program can perform various operations, such as creating, opening, reading a file, or even
manipulating the data present inside the file.
This process is known as file handling .

Why Do We Need File Handling in C?


There are times when the output generated out of a program after its compilation and running do not
serve our intended purpose.
In such cases, we might want to check the program’s output various times.
Now, compiling and running the very same program multiple times becomes a tedious task for any
programmer.
It is exactly where file handling becomes useful.

A few reasons why file handling makes programming easier for all:

 Reusability: File handling allows us to preserve the information/data generated after we run the
program.
 Saves Time: Some programs might require a large amount of input from their users. In such
cases, file handling allows you to easily access a part of a code using individual commands.
 Commendable storage capacity: When storing data in files, you can leave behind the worry of
storing all the info in bulk in any program.
 Portability: The contents available in any file can be transferred to another one without any data
loss in the computer system. This saves a lot of effort and minimises the risk of flawed coding.

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.

TYPES OF FILES
There are three types of file :

Text file

 A text file is a file that contains data in the form of characters.


 Each character is stored as an ASCII code or Unicode in the file. So while opening a text file text
editor translate each ASCII value and show us equivalent character that is readable by human
being.
 A text File can be created and edited using a text editor such as Notepad or a WordPad.
 A text File can have a different extension such as .txt, csv, .py etc depending on the format for the
content of the file.
 Each line of text file is terminated by special character called the End of Line(EOL).
 In a text file are usually separated by white space, but comma(,) and tab(\t) are also commonly
used to separate of values in text file.

Binary file

 A Binary file is a file that contains the data in the form of the bytes. Each byte is stored as a
sequence of 8 bits (0s and 1s) in the file.
 A binary file can store any type of data such as images, audio, video ,executable code etc.
 A binary file cannot be created or edited using a text editor but require specific program or
application that can understand its format.
 A binary file can have a different extension such as a dot bmp.mp3.exe etc depending on the
format of the content of a file.

Csv file

 CSV stands for Comma separated values.


 A CSV file is a plain text file that a stores data in the form of a table where each row is record and
each column is field.
 The data entries in each row are separated by commas,,hence the name of the format.
 CSV files are often used to store exchange a data between the different applications that can
handle that tabular data , such as spreadsheet databases ,contact managers etc.
 A CSV file can be opened an edited using a text editor or spreadsheet program such as Excel or
Google sheets.
 The extension of CSV files is usually “.CSV” .However, some programs or a systems may use
different extension for the CSV files such as “.txt” , “.tsv”, “.dat” etc.

Relative and Absolute paths

A path is a string that specifies the location of a file or folder in a file system . There are two types of
paths: relative and absolute.

Relative path

 A relative path is a path that is relative to the current working directory of the program or the user.
It describes the location of a file or folder without starting from the root of the file system.
 For example, if the current working directory is “D:\python programs”, then the relative path of
“Book.txt” in the same folder is just “Book.txt”. Similarly, the relative path of “Chapter1.txt” in a
subfolder named “Chapters” is “Chapters\Chapter1.txt”.
 A relative path can use “…” to refer to the parent folder of the current working directory. For
example, if the current working directory is “D:\python programs\Chapters”, then the relative path
of “Book.txt” in the parent folder is "…\Book.txt".

Absolute path

 An absolute path is a path that starts from the root of the file system . It describes the location of a
file or folder regardless of the current working directory of the program or the user.
 For example, the absolute path of “Book.txt” in “D:\python programs” is “D:\python programs\
Book.txt”. Similarly, the absolute path of “Chapter1.txt” in a subfolder named “Chapters” is “D:\
python programs\Chapters\Chapter1.txt”.
 An absolute path always starts with a drive letter (such as “C:”, “D:”, etc.) followed by a colon
and a backslash.

Text File

Opening a text file


To open a text file in Python, we use the built-in function open() . The open() function takes two
arguments: the name of the file and the mode of opening. The name of the file can be a relative or absolute
path , and the mode of opening can be one of the following:

Mode Description

“r” Open a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.

“r+” Open a file for both reading and writing. The file pointer is placed at the beginning of
the file.

“w” Open a file for writing only. Overwrites the file if it exists. Creates a new file if it
does not exist.

“w+” Open a file for both writing and reading. Overwrites the existing file if it exists.
Creates a new file if it does not exist.

“a” Open a file for appending. The file pointer is at the end of the file if it exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for
writing.

“a+” Open a file for both appending and reading. The file pointer is at the end of the file if
it exists. The file opens in the append mode. If the file does not exist, it creates a new
file for reading and writing.

The syntax of open() is as follows:

file_object= open(file_name, access_mode)

This function returns a file object called file handle which is stored in the variable file_object . We can use
this variable to transfer data to and from the file (read and write) by calling the functions defined in the
Python’s io module . If the file does not exist, the above statement creates a new empty file and assigns it
the name we specify in the statement.

For example, to open a file named “Book.txt” in read mode, we can write:

f = open("Book.txt", "r")

Closing a text file


To close a text file in Python, we use the close() method of the file object. The close() method releases the
resources associated with the file and ensures that any changes made to the file are saved. It is important to
close a file after using it to avoid errors or data loss.

The syntax of close() is:

file_object.close()

Here, file_object is the object that was returned while opening the file.

For example, to close the file object f, we can write:

f.close()

Opening a file using with clause

Another way to open and close a text file in Python is to use the with clause. The with clause creates a
context manager that automatically closes the file when the block of code under it is finished. This way,
we don’t have to worry about closing the file manually or handling any exceptions that may occur while
working with the file.

The syntax of with clause is:

swith open (file_name, access_mode) as file_ object:

For example, to open a file named “Book.txt” in read mode using the with clause, we can write:

with open("Book.txt", "r") as f:

# do something with f

Writing to a text file

For writing to a file, we first need to open it in write or append mode .

If we open an existing file in write mode , the previous data will be erased , and the file object will be
positioned at the beginning of the file.

On the other hand, in append mode , new data will be added at the end of the previous data as the file
object is at the end of the file.

After opening the file, we can use the following methods to write data in the file.

write() - for writing a single string

writelines() - for writing a sequence of strings

The write() method takes a string as an argument and writes it to the file.

The writelines() method takes a list of strings as an argument and writes them to the file as separate lines.

For example, to write some data to a file named “Book.txt” in write mode, we can write:
with open("Book.txt", "w") as f:

f.write("This is a book.\n")

f.write("It has many pages.\n")

f.writelines(["It is written by an author.\n", "It is published by a publisher.\n"]

Reading from a text file

We can write a program to read the contents of a file. Before reading a file, we must make sure that the file
is opened in “r”, “r+”, “w+” or “a+” mode. There are three ways to read the contents of a file:

The read( ) method

This method is used to read a specified number of bytes of data from a data file .

The syntax of read() method is:

file_object.read(n)

If no argument or a negative number is specified in read(), the entire file content is read.

The readline(n) method

This method reads one complete line from a file where each line terminates with a newline (\n) character.
It can also be used to read a specified number (n) of bytes of data from a file but maximum up to the
newline character (\n).

The syntax of readline() method is:

file_object.readline(n)

If no argument or a negative number is specified, it reads a complete line and returns string.

To read the entire file line by line using the readline() , we can use a loop . This process is known as
looping/ iterating over a file object . It returns an empty string when EOF is reached

The readlines( ) method

The method reads all the lines and returns the lines along with newline as a list of strings.
When we read a file using readlines() function, lines in the file become members of a list, where each list
element ends with a newline character (‘\n’).

The syntax of readlines( ) method is:

file_object.readlines()

Seek and tell methods

To get or set the position of the file pointer in a text file in Python, we use the tell() or seek() methods of
the file object.

Seek method

This method is used to position the file object at a particular position in a file.

The syntax of seek() is:

file_object.seek(offset [, reference_point])

In the above syntax,

offset is the number of bytes by which the file object is to be moved.

reference_point indicates the starting position of the file object. That is, with reference to which position,
the offset has to be counted. It can have any of the following values:

0 - beginning of the file

1 - current position of the file

2 - end of file

Tell method

This function returns an integer that specifies the current position of the file object in the file. The position
specified is the byte position from the beginning of the file till the current position of the file object.

The syntax of using tell() is:

file_object.tell()

Creating and Traversing a text file

To create a text file in Python , we use the open() function with the “w” or “a” mode . The “w” mode
creates a new file or overwrites an existing file, while the “a” mode creates a new file or appends to an
existing file.

For example, to create a text file named “practice.txt” in write mode, we can write:

f = open("practice.txt", "w")
To traverse a text file in Python , we use a loop to iterate over the lines or characters in the file. We can use
the readlines() method to get a list of all the lines in the file, or the read() method to get the entire content
of the file as a single string.

For example, to traverse a text file named “practice.txt” in read mode, we can write:

f = open("practice.txt", "r")

lines = f.readlines() # get a list of lines

for line in lines: # iterate over each line

print(line) # print the line

f.close() # close the file

OR

f = open("practice.txt", "r")

data = f.read() # get the whole content as a string

for char in data: # iterate over each character

print(char) # print the character

f.close() # close the file

You might also like