简体   繁体   中英

create a table using file contents python

if the file for example contains:

  • A: GHJIG
  • B: AHYFASF
  • C: IYDDFG

f = open(example.txt)

I want to store the file contents in a table and then the program should ask the user to enter a character and print the line without the alphabet.

  • input: A
  • output: GHJIG

how to do it?

Try this:

with open('test.txt','r') as file:
    content = file.readlines()

my_dict = {}

for line in content:
    split = line.split(':')
    my_dict[split[0]] = split[1]

input = raw_input("Choose a letter")

if input in my_dict:
    print my_dict[input] 

It would be better to use a OrderedDict from collections, because default dictionary has a not a precise order.

Try the solution below, you can provide a useful message if the user enters any alphabet which is not present in your txt file.

with open('/home/pydev/Desktop/t1.txt', 'r') as file_obj:
    content = file_obj.readlines()

sample_dict = {}
for value in content:
    sample_dict[value.split(':')[0]] = value.split(':')[1]

input_key = raw_input("Please enter an alphabet: \n")
print sample_dict.get(input_key, "No value exists")

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