VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-use-words-in-a-text-file-as-variables-in-python/

⇱ How to Use Words in a Text File as Variables in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Use Words in a Text File as Variables in Python

Last Updated : 23 Jul, 2025

We are given a txt file and our task is to find out the way by which we can use word in the txt file as a variable in Python. In this article, we will see how we can use word inside a text file as a variable in Python.

Example:

Input: fruits.txt
apple
banana
orange
Output:
apple = Fruit
banana = Fruit
orange = Fruit
Explanation: Here, we are using the content inside the fruits text file indicating that all the values inside the file is a fruit.

How to Use Words in a Text File as Variables in Python

Below are some of the ways by which we can use words in a text file as a variable in Python:

fruits.txt

apple
banana
orange

Reading Words from a Text File

In this example, a Python script reads words from a file named "fruits.txt" and assigns "Fruit" to each word as a label. It achieves this by first storing the file's lines and then iterating through them, stripping whitespace and adding each word to a list. Finally, it loops through the word list, printing each word followed by " = Fruit".

Output:

apple = Fruit
banana = Fruit
orange = Fruit

Using List Comprehension

In this example, a Python script efficiently reads words from "words.txt". It employs a single line of list comprehension to achieve this. The list comprehension iterates through each line in the file, removes whitespace with strip(), and builds a list containing all the words.

Output:

apple = Fruit
banana = Fruit
orange = Fruit

Using File Iteration

In this example, a concise Python script processes a text file "words.txt". It iterates through each line, removes whitespace using strip(), and directly prints each word labeled as "Fruit".

Output:

apple = Fruit
banana = Fruit
orange = Fruit
Comment