如何选择打开特定的文本文件

时间:2015-07-04 20:35:43

标签: python sorting

menu = {}
menu['1']="1" 
menu['2']="2"
menu['3']="3"
while True: 
  options=menu.keys()
  options.sort()
  for entry in options: 
      print (entry, menu[entry])

    selection = input('Please Select:')

    if selection =='1':
        file = open("1.txt")      
    elif selection == '2':
        file = open("2.txt")     
    elif selection == '3':
        file = open("3.txt")    

您好我希望能够选择要打开的特定文本文件。所以说如果' 1'输入文本文件打开等等。

3 个答案:

答案 0 :(得分:0)

这会将用户的选择放入要打开的文件字符串中。

menu = {}
menu['1']="1" 
menu['2']="2"
menu['3']="3"
while True: 
  options=menu.keys()
  options.sort()
  for entry in options: 
      print (entry, menu[entry])

    selection = input('Please Select:')
    file = open("{}.txt".format(selection))  

答案 1 :(得分:0)

您应该能够将输入前置到文件名的字符串:

selection = input('Please Select:')
file = open(selection + ".txt")

这可能不安全,因为用户可能能够指定自己的文件名。

您可能希望使用您的hashmap,以便.txt字符串前面的文本永远不会是列表中的内容:

selection = input('Please Select:')
file = open(menu[selection] + ".txt")

答案 2 :(得分:0)

不确定dict值是如何适合它的,但如果文件编号,你可以使用str.format打开文件:

menu = {'1': "1", '2': "2", '3': "3"}
options = sorted(options.items())
while True:
    for entry, v in options:
        print (entry, v)   
        selection = input('Please Select:')
        if selection in menu:
            break
        print("Invalid choice")

with open("{}.txt".format(selection)) as f:
        ...

如果您实际使用的是dict值,只需检查选择是否有效,即在dict键中,然后使用值打开:

menu = {'1': "1.txt", '2': "2.txt", '3': "3.txt"}
options = sorted(options.items())
while True:
    for entry, v in options:
        print (entry, v)
        selection = input('Please Select:')
        if selection in menu:
            break
        print("Invalid choice")
with open(menu[selection]) as f:
                ...

如果你使用的是你必须使用的python3,你不能在dict.keys上调用sort作为.keys()返回一个dictview对象而不是列表,所以options = sorted(options.items())实际上会给你一个排序列表您可以在for循环中解压缩的项目。