AppDividend
Latest Code Tutorials

How to Read File into List in Python

0

In Python, the contents of the file are a sequence of characters. The characters are represented as a list of values by splitting on a delimiter.

Python read file into list

To read a file into a list in Python, use the file.read() function to return the entire content of the file as a string and then use the str.split() function to split a text file into a list.

To read a file in Python, use the file.read() function.

The string split() is a built-in Python function that splits the string into the list. The split() method returns the list of strings after breaking the given string by a specified separator.

Let’s define the apple.txt text file in the same directory as our Python program file.

apple, microsoft, amazon, alphabet, facebook

It is a comma-separated value inside the apple.txt file.

We will read this file using a Python file.read() function and split the string into the list.

txt_file = open("apple.txt", "r")
file_content = txt_file.read()
print("The file content are: ", file_content)

content_list = file_content.split(",")
txt_file.close()
print("The list is: ", content_list)

Output

The file content are:  apple, microsoft, amazon, alphabet, facebook
The list is:  ['apple', 'microsoft', 'amazon', 'alphabet', 'facebook']

And you can see that we successfully read a file content into the list.

Using file.readlines() function

The readlines() is a built-in Python method that returns a list containing each line in the file as a list element. The readlines() function returns all the lines in the file as a list where each line is an item in the list object.

txt_file = open("apple.txt", "r")

content_list = txt_file.readlines()
print(content_list)

Output

['apple, microsoft, amazon, alphabet, facebook']

You can see that we read the text file into a list using the file.readlines() function in one step.

If the entire content of the file is all on one line, the file.readlines() function will return the list containing one item instead of a list of individual elements.

The file method readlines() reads until EOF using readline() and returns a list containing the lines.

That is it for reading a file into the list in the Python tutorial.

 

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.