Python Read a Text File: Add to List

4/5 - (1 vote)

βœ… Problem Formulation: You have a text file with multiple lines of data that you need to import into a Python list. Each line of the text file should be a separate element in the list. For example, if your file contains lines of quotes, you want to read each quote into a list where each quote is an individual item in that list.

Method 1: Using a for-loop with file open

The for-loop combined with the open() function in Python allows you to read a file line by line and append each line to a list. It is a straightforward approach that involves opening the file, iterating over each line, and adding each line to the list.

Here’s an example:

quotes_list = []
with open('quotes.txt', 'r') as file:
    for line in file:
        quotes_list.append(line.strip())

print(quotes_list)

The open function opens ‘quotes.txt’ for reading ('r'). The for loop iterates over each line in the file, the strip function removes leading and trailing whitespaces (including newline characters), and then each line is appended to quotes_list.

πŸ‘‰ Best 5 Ways to Read a Text File into a List of Numbers in Python

Method 2: Using list comprehension

List comprehension is a compact way to process all items in an iterable and return a list. When combined with a file object, it provides an elegant way to read lines from a file into a list in just a single line of code.

Here’s an example:

with open('quotes.txt', 'r') as file:
    quotes_list = [line.strip() for line in file]

print(quotes_list)

This code snippet uses list comprehension to create quotes_list. It opens the file, reads each line, strips the newline characters, and then compiles a list of the processed lines.

πŸ‘‰ How to Read a Text File Into a List or an Array with Python?

Method 3: Using the readlines() method

The readlines() method reads the entire file into memory and returns a list of its lines. This method is convenient but may not be memory-efficient for very large files.

Here’s an example:

with open('quotes.txt', 'r') as file:
    quotes_list = file.readlines()
    quotes_list = [line.strip() for line in quotes_list]

print(quotes_list)

This code reads all lines from 'quotes.txt' into a list with readlines(). Then, it uses list comprehension to strip the newline characters from each line.

Method 4: Using the map function

The map function applies a specified function to each item of an iterable and returns a list of the results. This can be used to apply the strip function to every line in the file.

Here’s an example:

with open('quotes.txt', 'r') as file:
    quotes_list = list(map(str.strip, file))

print(quotes_list)

The map function applies the strip method to each line of the file object. We convert the result of map into a list to get the quotes_list.

Bonus One-Liner Method 5: Using file object as iterator in list()

This one-liner uses the file object directly in the list() constructor, which is an implicit loop method, along with strip to remove the newlines.

Here’s an example:

quotes_list = list(line.strip() for line in open('quotes.txt', 'r'))
print(quotes_list)

This one-liner opens the file, reads, and strips each line, and finally, constructs a list out of the processed lines.

Summary/Discussion

  • Method 1: Using a for-loop with file open.
    • Strength: Easy to understand and debug.
    • Weakness: More verbose than other methods.
  • Method 2: Using list comprehension.
    • Strength: Compact and pythonic.
    • Weakness: Might be less readable for beginners.
  • Method 3: Using the readlines() method.
    • Strength: Provides a straightforward way to read a file into a list
    • Weakness: Not memory efficient for very large files.
  • Method 4: Using the map function.
    • Strength: Functional programming approach, concise.
    • Weakness: Somewhat less intuitive for those not familiar with functional programming concepts.
  • Bonus One-Liner Method 5: Using file object as iterator in list().
    • Strength: Extremely concise.
    • Weakness: Leaves the file open, which can lead to resource leaks if not handled properly.

πŸ‘‰ How to Read a File Line-By-Line and Store Into a List?