![]() |
VOOZH | about |
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.
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
orangeIn 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 = FruitIn 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 = FruitIn 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