Python reads the contents of a txt file and stores it in a dictionary

Reading a TXT File and Storing it in a Dictionary with Python

In Python programming, we often need to read text files and store their contents in a data structure for later use. This article will explain how to use Python to read the contents of a TXT file and store them in a dictionary (dict).

Preparation

Before reading a TXT file, we need to prepare a data sample. In this article, we will use the following sample.txt file as a sample. We will use a relative path to read the sample file, so please place it in the same directory as the .md file for this article.

The contents of the sample.txt file are as follows:

key1:value1
key2:value2
key3:value3

Reading a txt file

In Python, we use the built-in open() function to open files. The open() function accepts two parameters: the file path to be opened (relative or absolute) and the mode in which to open the file. In this article, we will open the sample file in read-only mode. The code is as follows:

with open('sample.txt', 'r') as file:
content = file.read()

In the code, the open() function returns a file object. We use the with statement to open and automatically close the file. We use the read() method to read the file contents and store them in the variable content. In this case, content stores a string, with each line separated by a newline character.

Parsing File Content

We’ve successfully read the contents of a txt file and stored them in the variable content. However, our goal is to store the file contents in a dictionary. Therefore, we need to parse the file content and convert it into key-value pairs. In this article, we’ll use colons to separate the key-value pairs on each line. The code is as follows:

result = {}
for line in content.split('n'):
if line:
key, value = line.split(':')
result[key] = value

In the code, we first define an empty dictionary, result, to store the parsed data. We then use a for loop to iterate over each line of the file content. Since each line is separated by a newline character, we use the split() method to split the string by the newline character and return a list. Next, we check each line. If it’s not empty, we use the split() method to separate the key-value pairs and store them in the dictionary result.

Output Result

We’ve successfully read the contents of the txt file and converted it into a dictionary. Now, we can use the print() function to output the dictionary’s contents to verify that our code is correct. The code is as follows:

print(result)

Executing the above code will result in the following output in the console:

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

The above output shows that we have successfully read the contents of the txt file into the dictionary. At this point, we can retrieve the value of the key based on the key. For example, result[‘key1’] will return ‘value1’.

Complete Code

Putting the above code together, we get the following complete code:

with open('sample.txt', 'r') as file:
content = file.read()

result = {}
for line in content.split('n'):
if line:
key, value = line.split(':')
result[key] = value

print(result)

Summary

This article introduced how to use Python to read the contents of a txt file and store it in a dictionary. In this article, we learned about Python’s built-in open() function and how to open a file and read its contents. We also learned how to convert a string into a dictionary and completed data parsing and storage. In real-world projects, we sometimes need to read large amounts of data. In these cases, we can use more efficient methods to read and parse data, thereby improving program execution efficiency. We should also pay attention to file path issues and use relative or absolute paths to open files. I hope this article can be helpful to Python beginners.

Leave a Reply

Your email address will not be published. Required fields are marked *