简体   繁体   中英

python- printing from a file when s user asks for input

i have successfully been able to import the text file and store it in a dictionary.i want to be able to ask the user to enter the number he wants and print the values corresponding to the number the user wants. example the file contains 2 names 1: chris 2:sam... i want the program to ask the user for an inputand the user puts in 2 it should print sam from the dictionary.

here is my code:

file = open("songranks.txt","r")
d={}

#Repeat for each song in the text file
for line in file:

  #Let's split the line into an array called "fields" using the "," as a separator:
  fields = line.split(",")

  #and let's extract the data:
  songrank = fields[0]
  list =[fields[1],fields[2]]
  k = [str(x) for x in list]
  ["".join(k)]
  chris=len(k)-1
  k=k[0:chris]
  d[songrank]=k


#It is good practice to close the file at the end to free up resources
file.close()

Any help would be appreciated.

To get the input in python:

question = input('ask your question')

Then play with the answer stored as a string. So from what you are saying something like:

print(d[int(question)])

You have to use input() function to get user input and some changes below I suggest to make your program more compact and clear.
We should refrain from using variable name which matches the reserved keywords like list , input , and , or etc. that is why you should change variable list to some other name.

file = open("songranks.txt","r")
d={}

#Repeat for each song in the text file
for line in file:

  #Let's split the line into an array called "fields" using the "," as a separator:
  fields = line.split(",")

  #and let's extract the data:
  songrank = fields[0]
  li =[fields[1],fields[2]]
  k = ["".join(str(x)) for x in li][0]
  d[songrank]=k


#It is good practice to close the file at the end to free up resources
file.close()
# yes indeed it is good practice

get_track_id = input("Enter track id") # Ask for input
print(d[get_track_id]) # print the track name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM