In this tutorial, we will learn how to convert a text file into a list in Python. This is a useful technique when working with large amounts of data or analyzing text from a file.
Being able to convert the contents of a file into a Python list allows us to perform operations on the data, such as sorting, searching, and filtering.
Step 1: Open the Text File
First, you need to have a text file that you would like to convert into a list. We’ll use a hypothetical file named “example.txt” for this tutorial. Here is the content of this file:
Apple Banana Cherry Date Fig Grape
To begin, we need to open the text file in Python using the open()
function. This function takes two arguments: the file name (as a string) and the mode in which to open the file (also a string). In our case, we’ll use the 'r'
mode for reading.
1 |
file = open('example.txt', 'r') |
Step 2: Read the Contents of the File
Next, we will read the contents of the file using the read()
method of the file object.
1 |
file_contents = file.read() |
This will read the entire contents of the file into a single string.
Step 3: Split the String into a List
Now that we have the contents of the file as a string, we need to split it into a list. We can do this using the splitlines()
method, which splits the string at line breaks (\n
) and returns a list of lines.
1 |
lines_list = file_contents.splitlines() |
Step 4: Close the File
We are now done reading the file, so it’s important to close it using the close()
method of the file object. This frees up any system resources tied to the file.
1 |
file.close() |
Step 5: Display the Result
Finally, let’s print the resulting list of lines to the screen to see the outcome of our code.
1 |
print(lines_list) |
The output will be:
['Apple', 'Banana', 'Cherry', 'Date', 'Fig', ' Grape']
Full Code
Here is the complete code for this tutorial:
1 2 3 4 5 |
file = open('example.txt', 'r') file_contents = file.read() lines_list = file_contents.splitlines() file.close() print(lines_list) |
Conclusion
In this tutorial, we learned how to convert a text file into a list in Python. This technique can be extremely helpful when working with large datasets or analyzing the contents of a file. By following these simple steps, you can now easily convert a text file into a list using Python.