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.
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:
Below program reads the data:
f = open('readme.txt', 'r') content = f.read() f.close() content_list = content.split(',') print(content_list)
- 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']
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.
- Python numpy interp method example
- How to use empty_like in numpy with example
- 3 ways to concatenate tuple elements by delimeter in Python
- How to iterate and print an array in reverse order in Python
- How to use Python numpy.all method with examples
- Python program to convert a dictionary to JSON
- How to convert a dictionary to string in Python