![]() |
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 PythonBelow 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 FileIn 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 ComprehensionIn 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
Output: apple = Fruit
banana = Fruit
orange = Fruit Using File IterationIn this example, a concise Python script processes a text file “words.txt”. It iterates through each line, removes whitespace using
Output: apple = Fruit
banana = Fruit
orange = Fruit |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 19 |