Loading...

File handling in Python – Complete Guide

File handling in Python – Complete Guide

If you are a Python programmer and want to expand your knowledge about file handling? Look no further! In this article, we will cover everything from the definition of file handling to its benefits. Also, we will cover creating, writing, and reading files in Python. So without further ado, let’s get started.

Introduction

First of all, let us define what file handling in Python really means, list the benefits, and the basic access modes used. File handling is an essential skill a programmer must have when working with data in Python.

Definition of File Handling in Python

File handling refers to the ability to read from, write to, and append to, basically manipulating files with a Python program. This also allows you to store and retrieve data from external sources, such as text files, CSV files, and databases.

Benefits of File Handling in Python

But why is file handling in Python so important? Here are a few key benefits:

  • It enables you to store data in a structured manner, such as in a text file or a CSV file. This can be particularly useful when working with large amounts of data that can’t be stored in memory.
  • It also allows us to read or write data from external resources, which include databases and web-based APIs. This can be helpful when working with data that needs to be shared with other systems or when retrieving data from external sources.
  • It gives you the ability to manipulate data, such as by sorting or filtering it. This can be useful when working with large datasets and needing to extract specific pieces of information.

There are six access modes in Python

In Python, there are six different access modes that you can use when working with files:

  • r – Read-only mode. This mode allows you to read from the file, but you can’t make any changes to it. It raises an error if the file is not existing on your system.
  • w – Write-only mode. This mode allows you to write to the file, but you can’t read from it. It creates the file if it does not exist on your system. It will overwrite if the file is present in your system.
  • a – Append-only mode. This mode allows you to write to the file, but you can’t read from this mode. It creates the file if it does not exist on your system. It will add new data if the file already has data.
  • r+ – Read + Write mode. This mode allows you to read from and write to the file. It raises an error if the file is not existing on your system.
  • w+ – Write + Read mode. This mode allows you to read from and write to the file. It creates the file if it does not exist on your system. It will overwrite if the file is present in your system.
  • a+ – Append + Read mode. This mode allows you to read from and write to the file. It creates the file if it does not exist on your system. It will add new data if the file already has data.

How to Create Files in Python

Now that we know the different access modes, let’s talk about how we can create a file in Python. To do this, we will use the built-in open() function. The main characteristic of this function is that it only takes two arguments, which include the file name and the access mode.

For instance, if we want to create a new text file called “mynewfile.txt” in write mode, you can refer to the following code:

f_new = open("my_new_file.txt", "w")
Code language: Python (python)

The above code will tell Python to create the file automatically if the file doesn’t exist. If the file does exist, it will be overwritten.

We must however remember that we must always close a file when we are finished working with it in Python. This releases the resources that the file you created was using and allows the other programs to access the file. We use the close() method for the same The for it is as follows:

f_new = open("my_new_file.txt", "w") # New file created to write in the file f_new.close()
Code language: Python (python)
Output

Alternatively, we can use the with statement to automatically close the file after you’re finished working with it. The with statement creates a context in which the file is open, and when the block of code within the with statement is finished, the file closes automatically. We often consider it as the best practice when working with files in Python.

For example:

with open("mynewfile.txt", "w") as f_new: # new file created # alternate way to write to the file
Code language: Python (python)
Output

Click Here to try the above codes.

How to Write to a File in Python

Now that we know how to create a file in Python, let us now discuss how to write in a file. There are two main methods for doing this:

This method is called write()

The write() method is usually used when we have to write a single string to a file. It takes a string as an argument and writes it to the file.

For example, to write the following string to a file called “write_file.txt”, you can use the following code:

with open("write_file.txt", "w") as f: f.write("Hello, World!\n") f.write("This a text file\n") f.write("Bye!\n")
Code language: Python (python)
Output

This method is called writelines()

The writelines() method is used when we have to write a list of strings in a text file. This method takes a list of strings and writes each string entered by the user to the file, with a newline character after each string.

For example, to write the strings to a file called “myfile.txt”, you can use the following code:

with open("my_write_file.txt", "w") as f: f.writelines(["Hello\n", "World\n","this is example for\n","writelines\n"])
Code language: Python (python)
Output

Click Here to try the above codes

It’s important to note that when using the write() and writelines() methods, the file must be opened in a mode that allows writing, such as ‘w’, ‘w+’, or ‘a’

How to Read data From a Text File in Python

Now that you know how to write onto a file in Python, It’s time we discuss the next step which is how to read data from a text file. Today we will go through three main methods:

This is the sample text file, you can refer to which we will use to execute the following methods.

Sample file

Method the read()

To read all the contents of the file in one go, we use the read() method. It returns all content of the file in the form of a string.

For example, to read the contents of the file “myfile.txt”, you can use the following code:

with open("my_read_file.txt", "r") as f: contents = f.read() print(contents)
Code language: Python (python)
Output

Method the readline()

If you want to read a single line from the text file then we use the readline() method, which returns the text present in the file as a string. Once the end of the file occurs, python returns an empty string.

For example, if you want to read the first line of the file “my_read_file.txt”, you can use the following code:

with open("my_read_file.txt", "r") as f: line_read = f.readline() print(line_read)
Code language: Python (python)
Output

If you want to display or read each line of the file one by one we can use the ‘for’ loop. Refer to the following example for the same:

with open("my_read_file.txt", "r") as f_line: dis_line = f.readline() while line: # here we will read a line from the file dis_line = f_line.readline() print(dis_line)
Code language: Python (python)
Output

Method the readlines()

If you want to print all the lines of a text file then you can use the readlines() method, this returns the lines of files in the form of a list of strings, one string element of the list represents a line of the file.

For example, if you want to read the contents of the file “my_read_file.txt” and store it as a list of lines, we can use the following code:

with open("my_read_file.txt", "r") as f_lines: display_lines = f_lines.readlines() print(display_lines)
Code language: Python (python)
Output

Click Here to try the above codes.

One thing you must remember while the above methods are that your open must be in ‘r’ or ‘r+’ mode.

How do you close a Text File in Python?

Finally, you have arrived at the last topic for today’s article. Here we will talk about how to close a text file in Python. You must wonder why we should close a file. Well, it’s important because once you close the file python will release its resources and make the file available for other programs to access the file. To close a text file we can use the close() method.

For example:

f = open("file_close.txt", "r") contents = f.read() print(contents) f.close()
Code language: Python (python)
Output

Alternatively, we can use the with statement. the main characteristic of this statement is that it automatically closes the file once the user is finished working on it. For example:

with open("file_close.txt", "r") as f: contents = f.read() print(contents)
Code language: Python (python)
Output

Click Here to try the above codes.

Conclusion

To conclude today’s article we discussed File handling in Python. It is a powerful tool for working with data from external sources. By using the built-in open() function and the various read and write methods, we can easily read from and write to text files in Python. Remember to always close a file when we finish working with it, to release the resources it was using and allow other programs to access the file. Whether you are reading data from a file to perform analysis, writing data to a file to share with others, or manipulating data in a file to meet your needs, file handling in Python can help you work with data efficiently and effectively.

I hope my article is helpful. I will be grateful if you could share this article with your friends. Queries are always welcome in the comment section. We will be back soon with another fantastic article. Till then, keep coding.

Sharing is caring

Did you like what Pravin Gupta wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far

Curious about this topic? Continue your journey with these coding courses: