Python 如何选择打开特定文本文件
嗨,我想能够选择一个特定的文本文件打开。因此,如果输入了“1”,文本文件将打开,依此类推。这将把用户的选择放入要打开的文件字符串中Python 如何选择打开特定文本文件,python,sorting,Python,Sorting,嗨,我想能够选择一个特定的文本文件打开。因此,如果输入了“1”,文本文件将打开,依此类推。这将把用户的选择放入要打开的文件字符串中 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 = inpu
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")
您应该能够将输入前置到文件名的字符串:
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))
但这可能不安全,因为用户可以指定自己的文件名
您可能希望改用hashmap,以使.txt字符串前面的文本永远不会是列表中的文本以外的任何内容:
selection = input('Please Select:')
file = open(selection + ".txt")
不确定dict值是否适合该文件,但如果文件已编号,则可以使用str.format打开该文件:
selection = input('Please Select:')
file = open(menu[selection] + ".txt")
如果您实际使用的是dict值,只需检查选择是否有效,即在dict键中,然后使用以下值打开:
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:
...
如果您使用的是python3,您必须看起来像是python3,那么就不能在dict.keys上调用sort,因为.keys()返回的是dictview对象而不是列表,所以options=
sorted(options.items())
实际上会为您提供一个可在for循环中解包的项目的排序列表。您应该添加一些与正在使用的技术相关的标记。您的解决方案有什么问题?
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:
...