How to Store list items in a text file in Python

In this tutorial, we will learn how to store list in a text file in Python

Store list items in a text file in Python

Code and Explanation :

# Enter the number of items
n = int(input("Enter the number of items you want to add to the list: "))

# Initialize an empty list to store the items
items = []

# Enter each item
for i in range(n):
    item = input(f"Enter item {i+1}: ")
    items.append(item)

# Open a file in write mode
with open("Trial.txt", "w") as file:
    # Write each item in the list to the file
    for item in items:
        file.write(item + "\n")

print("Items have been written to Trial.txt")
  • Enter the ‘n’ number of items they want to add to the list.
  • Initializes an empty list called ‘items’ to store the user input.
  • Entering items in the empty list ‘items
    1. Run the loop till ‘n‘ times
    2. Inside the loop the user will input the item which he/she wants to store.
    3. The item will be inserted into list ‘items‘ using the command ‘items.append‘.
  • A file named ‘Trial.txt’ open in write mode using command ‘open(“Trial.txt”, “w”)’.
  • The ‘with‘ statement ensures that the file is properly closed after writing.
  • The loop ‘item‘ iterates over each item in the list and writes it to the file using command ‘file.write()’, followed by a newline character (\n). This ensures that each item is written on a new line in the text file.
  • Display a message to show that the items are stored in Trial.txt.

Sample Output:

  • Enter the number of items you want to add to the list: 5
  • Enter item 1: codespeedy
  • Enter item 2: banana
  • Enter item 3: apple
  • Enter item 4: tomato
  • Enter item 5: carrot
  • Items have been written to Trial.txt

Trial.txt

codespeedy
banana
apple
tomato
carrot

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top