Text File with Python featured image

The txt File Format: Working with Plain Text Files in Python 3

Introduction

One of the primary functions of programming languages is to help you deal with data. This includes data writing, reading, storage, as well as transfer. Python is one of the most popular programming languages. If you are planning to use Python, you should have a basic idea of how to use different file types. The simplest of file types is the txt or plain text file format. Consider that you have a program that checks users for access control. The list itself will be saved as a text file. Thus, while you may use another program for certain corporations, you will extract the values from a text document. That is why it is important to understand the text file format.

In this tutorial, we start with a brief background about the basic file formats in Python. Then we will discover how to open, read, and write text files in the program.

Before We Begin…

Before we start with the tutorial, there are some prerequisites you need to fulfill. First, you should have already installed Python 3. In addition to that, you need a local programming environment on your system. This tutorial is applicable to Ubuntu 16.04 and above, Debian 8, CentOS 7, Mac OS X, and Windows 10.

File Formats

There are various file formats that you can utilize in Python. The below table lists all the different formats and where you can use them:

File type Description
txt Plain text file stores data that represents only characters (or strings) and excludes any structured metadata.
CSV Comma-separated values file uses commas (or other delimiters) to structure stored data, allowing data to be saved in a table format.
HTML HyperText Markup Language file stores structured data and is commonly used with most websites.
JSON JavaScript Object Notation is a simple and efficient format, making it one of the most commonly used formats to store and transfer data.

In this tutorial, we will explore the txt file format in further detail.

Step 1: Text File Creation

First, we must create a new text file in Python. We will consider an example for the days of the week for understanding purposes. For this, we will open the text editor, make a new txt file, and call it days.txt. Next, let’s enter the days of the week as individual lines in the new file:

Now that we have the content, we will save the file. It is important to make a mental note of where you save the file. Let’s say our user is sammy. The user has saved the file on the following path: /users/sammy/days.txt. We will be using this path in future processes.

Step 2: Text File Opening

Before you can start with writing a program, you must create a file in the editor. We will make a file called files.py and save it in the /users/sammy directory like our days.txt file.

To open any file, you have to start a connection between the disk file and the variable. This is what constitutes ‘opening’ the file. The location of the file is indicated by the path of the file. You need the path to open the file. For example, the path of the days.txt file is the following: /users/sammy/days.txt. Then, we will create a string variable to save this data. As you will see below, we will make a path variable in the files.py script and change the variable as per the days.txt path:

After that, using the open() function, we will open the days.txt file. For this function, you need to provide the file path. Among other parameters, the most important is the mode parameter. This is an optional string that you can add to specify the mode in which you open the file. Following are a few of the mode options:

  • 'r’: reading
  • 'w’: writing
  • 'x’: creating and writing a new file
  • 'a’: appending a file
  • 'r+’: reading and writing the same file

To simply read from the file, you need to use the 'r’ mode. Run the open() function and open the days.txt file. Next, assign it to the days_file variable:

Step 3: Text File Reading

After opening the file, we can read from it through the variable. There are three operations associated with file reading. Let’s explore all three.

The first operation is <file>.read(). It will show you the whole content of the file in one string:

Output:

The next operation is <file>.readline(). This will show you the next line in the file. It will essentially read the file line by line:

Output:

Calling the function once again will read the next line in the code. You may call it as follows:

Output:

The third and final operation is <file>.readlines(). It will show you a list of all the lines in the file. Each item represents one line:

Output:

Remember, once a file has been read, you cannot read it again. This is applicable regardless of the function you use. In order to read the file again using another operation, you must open a new file variable.

Step 4: File Writing

Next, we will learn how to write a new file. This file, in our example, will have the title (Days of the Week) and then the days of the week subsequently.

To begin with, we must create the title variable:

Next, we have to save the days of the week in the form of a string variable. This variable will be called days. We shall continue to use the code we used in the above steps. We will open the file in read mode and store the output into our new days variable:

This means that we have made variables for the title as well as the individual days of the week. Now we can write the file itself. The first step is to specify the file location using the directory /users/sammy/. In the path, you will also specify the new file: /users/sammy/new_days.txt. The location path will remain under the new_path variable. Next, open the file in write mode with the open() function in ‘w’ mode:

Now that the file is open, you can enter data using the write function <file>.write(). Here, you need to enter a single string parameter. If you want to enter a new line, enter the newline character. For our file, we will enter the title first and then the days of the week. Alongside, we will also have some print statements to track the progress of the script:

Step 5: File Closing

When you close the file, you are terminating the connection between the disk file and the file variable. When the file is closed, it can be accessed by other programs. This also helps to keep the file and its data safe. Therefore, always remember to close the files when you are done processing them. To do so, you may use the <file>.close() function:

That finishes the processing aspect of files in Python.

Step 6: Code Checking

Finally, we will check the code. You should do that before you run the code you wrote. The code should look something like this:

Once you save the code, you have to run the Python script. For that, you need to open the terminal:

It will show the following output:

To check your code, you will open the new file which is new_days.txt. If everything is fine, you will see the following:

If you see something similar to the above, you completed the steps successfully.

Conclusion

Through this tutorial, we aimed to teach you about the basic file formats in Python 3. Among these, one of the most critical is the text file format. We explored it in further detail. Now, you are well aware of the process and steps involved in opening, reading, writing, and closing data files. Using this information, you will be able to effectively utilize the text file format in your own Python programming experience.

Now that you have learned how to work with plain text files in Python, here are some more tutorials from our blog that will get you started on utilizing Python:

Happy Computing!