Python program to read the content of a file to a list

Python program to read the content of a file to a list:

In this post, we will learn how to read the content of a file to a list. The file will hold comma-separated strings and our program will read the strings, and put them in a list.

With this program, you will learn how to read the contents of a file and how to get the words from a comma-separated string in Python.

Method 1: Read the contents of a file by using the read() method:

Python file read() function can be used to read the content of a file. This function reads and returns the content as a string. As the content is comma-separated string, we can use split function to get the words from the string.

split takes the separator as the parameter. It breaks the string at the separator and creates one list from the split strings.

Let’s try it with an example. For this example program, we have created a file readme.txt with the following content:

one,two,three,four,five,six,seven,eight,nine,ten

Below program reads the data:

f = open('readme.txt', 'r')
content = f.read()
f.close()

content_list = content.split(',')

print(content_list)

Here,

  • The file is opened in read mode or r mode.
  • It reads the content of the file and that content is stored in the content variable.
  • Once the reading is done, we are closing the file by using the close() method.
  • By using split, it is splitting the string at , and the list is stored in current_list.

If you run this program, it will print the below output:

['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']

Method 2: Read the contents of a file by using the readlines() method:

If your words are in a new line in the file, i.e. one word per line, you can use readlines method. For example, if the file contains:

one
two
three
four
five
six
seven
eight
nine
ten

We can use readlines to read and put the strings in a list.

readlines method returns a list that holds each line of the file as a separate list item.

f = open('readme.txt', 'r')
content = f.readlines()
f.close()

print(content)

If you run this, it will print:

['one\n', 'two\n', 'three\n', 'four\n', 'five\n', 'six\n', 'seven\n', 'eight\n', 'nine\n', 'ten']

Optionally, we can also pass a number to readlines which defines the number of lines to read in the file. If you have a large file and if you want to read the line up to a specific line number, you can use this parameter.

You might also like: