File Handling In Python: An Interesting Guide For 2021

Introduction

File handling in Python is straightforward as it helps users manipulate files, such as read and write them, and a variety of other file handling options. The idea of file handling has been extended to various other languages, but the implementation is either difficult or lengthy. However, like other Python concepts, this concept is simple and straightforward. Python handles files differently depending on whether they are text or binary, which is crucial. Let’s 

Even though the two types of files in Python appear to be identical on the surface, they encode data differently.

A text file is made up of a series of lines. In addition, each line of the text file is made up of a series of characters. The end of the line is used to indicate the end of each line in a text file (EOL). A few special characters are used as EOL, but the most popular are the comma and newlines.

Binary files include image files such as .gif, .png, .jpg, and documents such as .pdf, .xls, .doc, and several others.

In this article let us look at:

  1. Opening a File
  2. Writing into a File
  3. Reading from a File
  4. Closing a File
  5. Python’s File Handling Programs

1. Opening a File

The first step is to open a file before performing any operations related to file handling in Python, such as reading or writing. Python has a built-in feature called open() that can be used to open a file. The name of the file and the access mode are the only parameters accepted by the open function. The access mode determines whether we are going to read or write to a file. The open() function returns a file object/handle, which can be used to perform operations related to file handling in Python, depending on the access mode.

Syntax:

file_object=open(filename, access_mode)

Example:

file_object=open(“test.txt”) # if the file is located in the current directory

file_object=open(“C:\User\Desktop\test.txt”) # If the file is in a different directory, define the full route.

2. Writing into a File

As an operation related to file handling in Python, the write() function is used to write into a file in one of the following two modes:

‘we Creates and writes to a new file. The file pointer is located at the start of the file. It overwrites the original file if it already exists.

‘a’: Add a new line to an existing file. The file pointer is at the file’s top. F a file does not exist, it is created.

The above-mentioned modes will answer the question of “How to write to a file in Python?”

3. Reading from a File

As an operation related to file handling in Python, the read() method is used to read data from a file. The file pointer is located at the start of the file.

A text file can be read in three different ways:

1) read() : The read bytes are returned as a string. Reads n bytes, or the entire file if no n is specified.

File_object.read([n])

2) readline() : Reads a single line from a file and returns it as a string. Reads at most n bytes for the listed n. Even if n is greater than the length of the line, it does not read more than one line.

File_object.readline([n])

3) readlines() : Reads all of the lines and returns a list with each line as a string part.

File_object.readlines()

4. Closing a File

If we’ve finished performing Python file operations, we must close it. When we close a file in Python, it releases all of the resources associated with it. To close a file, we use the built-in method close(). We can’t depend on Python’s garbage collector to close the file, despite its existence.

file_object=open(“test.txt”)

file_object.close()

If an exception occurs when performing a file operation, the code terminates without closing the file. As a result, using a try-finally block is a smart idea.

The benefit of using the ‘with’ expression is that it closes the file immediately, even though an exception occurs. If we use the ‘with’ expression, we don’t need the close() feature. It’s done on the inside. It is always a good idea to use the ‘with’ expression while dealing with files.

5. Python’s File Handling Programs

The following are the various tools or programs to perform operations related to file handling in Python:

  • rename(): It is a tool for renaming a file.
  • remove(): In Python, this tool is used to delete a file.
  • chdir(): It is a tool for changing the current directory.
  • mkdir(): It is a tool for creating a new directory.
  • rmdir(): It is a tool for removing a directory.
  • getcwd(): It is a tool that displays the current working directory.

Conclusion

So that brings us to the conclusion of our file handling in Python tutorial, in which we addressed the question, “How to handle files in Python?” Python file management and various file handling methods in Python file operations have also been discussed, with Python file handling examples that will come in handy when working on real-world projects.

If you are interested in making a career in the Data Science domain, our 11-month in-person Postgraduate Certificate Diploma in Data Science course can help you immensely in becoming a successful Data Science professional. 

ALSO READ

Related Articles

loader
Please wait while your application is being created.
Request Callback