Discover a world of knowledge at Westonci.ca, where experts and enthusiasts come together to answer your questions. Get quick and reliable solutions to your questions from a community of experienced professionals on our platform. Join our platform to connect with experts ready to provide precise answers to your questions in different areas.
Sagot :
The code:
filename = input("> ")
with open(filename, "r") as file:
items = file.read()
items = items.split("\n")
for index, item in enumerate(items):
items[index] = item.split("\t")
for item in items:
if item[3] == "Available":
print(f"{item[1]} ({item[0]}) -- {item[2]}")
Explenation:
1. We make the user enter the file's path, in our case "food.txt". This does only work if the .txt file is in the same directory as our code.
2. We get the content of our .txt file with the "open" function. If we use the "open" function inside of a "with" statement we don't have to deal with closing the file after we opened it. The file will close as soon as we exit the statement. The argument "r" indicates that we only want to read the file, not do anything else with it.
3. However the variable "file" doesn't contain the contents of "food.txt", only the class object of our file (if you try "print(file)" you'll only get nonsense). We can simply get the content of the file by calling ".read()" after.
4. We can separate this long str using the ".split()" function. The split function seperates a string by another sertain string (in our case "\n", since the different items are seperated by a newline). Now "items" is a list of strings.
5. Next we go through all items in "items" and separate them by "\t", again using the ".split()" function. Enumerate makes a list of indexes and values from another list (in our case, "items").
6. Now we have a list of lists of strings. The only thing left to do is go through every item and print it if the item's third item is equal to "Available" (notice that this is case-sensative). And print out the result in the desired format.
The code works for me, please ask me if there is anything you don't understand (or if the code is incorrect). Happy to help :D
Thank you for your visit. We're dedicated to helping you find the information you need, whenever you need it. Thank you for visiting. Our goal is to provide the most accurate answers for all your informational needs. Come back soon. We're dedicated to helping you find the answers you need at Westonci.ca. Don't hesitate to return for more.