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:
1 2 3 4 5 6 7 |
Monday Tuesday Wednesday Thursday Friday Saturday Sunday |
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:
1 |
path = '/users/sammy/days.txt' |
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:
1 |
days_file = open(path,'r') |
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:
1 |
days_file.read() |
Output:
1 |
'Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday\n' |
<file>.readline()
. This will show you the next line in the file. It will essentially read the file line by line:
1 |
days_file.readline() |
Output:
1 |
'Monday\n' |
1 |
days_file.readline() |
Output:
1 |
'Tuesday\n' |
<file>.readlines()
. It will show you a list of all the lines in the file. Each item represents one line:
1 |
days_file.readlines() |
Output:
1 |
['Monday\n', 'Tuesday\n', 'Wednesday\n', 'Thursday\n', 'Friday\n', 'Saturday\n', 'Sunday\n'] |
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:
1 |
title = 'Days of the Week\n' |
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:
1 2 3 |
path = '/users/sammy/days.txt' days_file = open(path,'r') days = days_file.read() |
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:
1 2 |
new_path = '/users/sammy/new_days.txt' new_days = open(new_path,'w') |
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:
1 2 3 4 |
new_days.write(title) print(title) new_days.write(days) print(days) |
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:
1 2 |
days_file.close() new_days.close() |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
path = '/users/sammy/days.txt' days_file = open(path,'r') days = days_file.read() new_path = '/users/sammy/new_days.txt' new_days = open(new_path,'w') title = 'Days of the Week\n' new_days.write(title) print(title) new_days.write(days) print(days) days_file.close() new_days.close() |
Once you save the code, you have to run the Python script. For that, you need to open the terminal:
1 |
$ python files.py |
It will show the following output:
1 2 3 4 5 6 7 8 9 |
Days of the Week Monday Tuesday Wednesday Thursday Friday Saturday Sunday |
To check your code, you will open the new file which is new_days.txt
. If everything is fine, you will see the following:
1 2 3 4 5 6 7 8 9 |
Days of the Week Monday Tuesday Wednesday Thursday Friday Saturday Sunday |
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:
- Using Python 3 String Formatters
- Loops in Python 3: Using Break, Continue, and Pass Statements
- Python 3: A Guide on Converting Data Types
- How to Crawl a Web Page with Scrapy and Python 3
Happy Computing!
- How To Enable, Create and Use the .htaccess File: A Tutorial - March 8, 2023
- An Overview of Queries in MySQL - October 28, 2022
- Introduction to Cookies: Understanding and Working with JavaScript Cookies - October 25, 2022
- An Overview of Data Types in Ruby - October 24, 2022
- The Architecture of Iptables and Netfilter - October 10, 2022