How to Read Text File Into List in Python?

Python is a versatile and powerful programming language, and one of its many features is the ability to read and write files.

In this blog post, we’ll be focusing on reading text files in Python and how to convert their contents into a list.


Opening a Text File

The first step in reading a text file in Python is to open it.

This is done using the built-in open() function. The function takes two arguments: the name of the file, and the mode in which to open the file.

In this case, we want to open the file in “read” mode, which is represented by the letter ‘r’.

file = open('text_file.txt', 'r')

Reading the Contents of the Text File

Once the file is open, we can read its contents using the read() method. This method will return the entire contents of the file as a string.

contents = file.read()
print(contents)

Splitting the Contents of the Text File into a List

Now that we have the contents of the text file as a string, we can convert it into a list.

This can be done using the split() method, which takes a delimiter as an argument and splits the string into a list at each occurrence of the delimiter.

text_list = contents.split()
print(text_list)

Closing the Text File

It’s important to close the text file when you are finished reading from it to free up system resources. This can be done using the close() method.

file.close()

Example

Here is a complete example that demonstrates how to read a text file into a list in Python:

# Open the text file
with open('text_file.txt', 'r') as file:
    # Read the contents of the file
    contents = file.read()
    # Split the contents of the file into a list
    text_list = contents.split()

# Print the list
print(text_list)

In this example, we open the text file text_file.txt in read mode, read the contents of the file into a string called contents, split the contents of the string into a list called text_list, and then print the list.

Another way of reading the file content and returning a list is using the readlines() method,

# Open the text file
with open('text_file.txt', 'r') as file:
    # Read the contents of the file into a list
    text_list = file.readlines()

# Print the list
print(text_list)

Conclusion

In this blog post, we’ve shown you how to read a text file in Python and convert its contents into a list.

We’ve also shown how it can be done using two methods and that is read() and readlines().

Remembering to close the text file is crucial step, using with statement takes care of closing the file for you, which makes it a preferred way of reading files.

With these simple steps, you can now read the contents of any text file into a list in Python with ease!