r/pythonhelp • u/Party_Manufacturer60 • Jan 26 '23
block of code reading imported .txt file for snowboarding program
beginner good with theory, extremely bad with practice.
I imported the following .txt file made up by my categories + the user input after the ": * + space*" in the code:
gender: f
bootsize: 38
brand: Burton
experience_level: beginner
riding_style: allmountain
height: 165
for category "riding_style" I would like the user to be able to give more than 1 answer, like "freestyle park" because with more than one answer the suggested snowboard profile will be different.
I am stuck because this block of code only gets the 1st word of the user input as a dictionary value because we wrote [1]
from typing import Dict, Any #review
def read_input():
name = "input.txt"
file = open(name, 'r')
text_lines = file.readlines()
for line in text_lines:
word_list = line.split()
key = word_list[0]
value = word_list[1]
dictionary_input = {key: value}
print(dictionary_input[key])
file.close()
return dictionary_inputI thought maybe I could write a special case in the for loop that for that specific riding_style line would take more than just 1 word after the first one and create a list with them and put the list as a value in the dictionary, but have no idea how. I looked online but I could find no answers.
Plus I am not sure how it would work and what if the user writes a comma or "and" between the words like "park and freestyle" or "park, freestyle" D:
Does anyone know a method or has tips? I am really quite desperate :/
LG
1
u/CraigAT Jan 26 '23
You should be able to what you want if you can use another separator maybe a "pipe" character or a hash (anything you wouldn't expect to be used in the data entry).
After you have read the line, use the split as usual to get your key (or the field name) if that matches "riding_style" then with the rest you split it that using the new separator and then use them however you planned to. If you plan to write it back to a file you put that separator inbetween each entry for that field.