Python

Understanding File Handling in Python

Understanding File Handling in Python

Introduction

Files are an essential part of any program to store, read and manipulate data. In this section, we will be focusing on reading, writing, and performing the basic operations on text files in Python. Python file handling involves a lot of methods, however, this article will provide a comprehensive understanding of the various methods available to manipulate the data using Python

File Handling Functions

1.Open()

Before performing any sort of operation on the file, the first thing which must be done is to open the file which can be done using the open method. It takes two parameters - file name and file mode. The file name specifies the location or the file name and file mode specifies the type of operation to be performed on the file. This method returns a file object which can be used to perform various operations on the file

The various file modes are specified below:

Syntax: file object = (file name, file mode)

File Mode

Purpose

r

Open a file for reading and throws an error if the file does not exist

w

Open a file for writing if it does not exists or overwrite the file if it already exists

a

Open a file for appending, and no data will be overridden

r+

Read and write data in a file, any existing file will be overwritten

w+

Read and write data in a file, any existing file will be overwritten

a+

Append and read data in a file, no data will be overridden

Code

#A File named boardinfinity will be created using write mode and opened

file = open('boardinfinity.txt', 'w')

2. With()

Similar to the open method, a file can be opened using the “with” method. The difference between the previous and the given method lies in the fact that all statements succeeding in this method are part of the block which is not the same in the previous open method. In addition, the file will be automatically closed once you’re done performing operations on the file

Syntax: with open(file name,file mode) as file object

Code

#A File named boardinfinity will be created using write mode and opened

with open('boardinfinity.txt', 'w') as file:

print("Using with method file is created")

3. Read()

Once the file is opened using the open or with the method, the data in it can be read using the read() method. If no argument is passed then the entire file is read otherwise n bytes of the file will be read.

Code

#A File named boardinfinity will be opened and the data will be printed

with open('boardinfinity.txt', 'r') as file:

data = file.read()

print(data)

Output

Board Infinity

Code

#A File named boardinfinity will be opened and the data will be printed up to specified bytes

with open('boardinfinity.txt', 'r') as file:

data = file.read(5)

print(data)

Output

Board

4. Write()

This method is used to write data into the file. If the file does not exist, then a new file will be created, or else the file opened will be overwritten

Code

#A File named boardinfinity will be opened and the data will be written into the file

with open('boardinfinity.txt', 'w') as file:

file.write("Hello Board Infinity")

Output

Hello Board Infinity

5. Append

This method is used to add data to an existing file. If the file does not exist, then a file will be created and data will be written inside it.

Code

#A File named boardinfinity will be opened and the data will be appended

with open('boardinfinity.txt', 'a') as file:

file.write("Welcome to Board Infinity")

Output

Hello Boar Infinity

Welcome to Board Infinity

6. Split()

This method splits a string into a list of values specified by a delimiter. In terms of file handling this can be demonstrated as follows:

Code:

#A File named boardinfinity will be opened and the data will be read and put into a list

with open('boardinfinity.txt', 'r') as file:

data = file.read()

l = data.split()

print(l)

Output:

[‘Hello’,’Board’,’Infinity’,’Welcome’,’to’,’Board’,’Infinity’]

Some other methods used to read and write are listed below for your reference:

7. readlines()

This method provides another way of reading the contents of a file. The important difference between the read and readlines method is that the lines read from the file are returned in the form of a list. Thus one can iterate through this list of lines and print the contents of the file.

Syntax: list = file_object.readlines()

8. writelines()

This is another method in addition to the write method. This method is used to write a list of lines as the contents of a file. An important thing to keep in mind while using this method is that the new line character has to be explicitly given by the user wherever it is required.

Syntax: list = [“Board Infinity\n”, “is the best\n”]

file_object.writelines(list)

9. rename()

rename() is a method that is present in the os module which is generally used when dealing with files. The main purpose of this function is to change the name of the current file to a new name and this can be done by using the syntax given below

Syntax: import os

os.rename(current_file_name, new_file_name)

10. remove()

This method is used to remove or delete a given file by passing the file name or the location of the file as a parameter. The syntax for this method is illustrated below:

Syntax: remove(file_name/file_location)

Conclusion

The different file operations were in the previous and after this, you will be able to manipulate data as well as read and write. Now you will be able to successfully handle text files in Python with the most important methods being - open() and with() to open files, read() , write() and append() to read, write and append data into your file.