Open In App

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

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".

# Open the file
with open("fruits.txt", "r") as file:
    # Read all lines from the file
    lines = file.readlines()

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

# Loop through each line in the file
for line in lines:
    word = line.strip()
    words.append(word)

# Now you can use the words as variables
for word in words:
    print(f"{word} = 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.

# Read words from the file using list comprehension
with open("words.txt", "r") as file:
    words = [line.strip() for line in file]

# Now you can use the words as variables
for word in words:
    print(f"{word} = Fruit")

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".

# Open the file
with open("words.txt", "r") as file:
    for line in file:
        word = line.strip()
        print(f"{word} = Fruit")

Output:

apple = Fruit
banana = Fruit
orange = Fruit
Article Tags :