Opening a file based on user's input python
如何根据用户输入的整数从给定文件列表中打开文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | print("Enter 1.tp.txt 2.c17testpat.pat 3.c432testpat.pat 4.c499testpat.pat 5.c1335testpat.pat 6.c6228testpat.pat") user = input("Enter a number") if user == 1: filename ="tp.txt" elif user == 2: filename ="c17testpat.pat" elif user == 3: filename ="c432testpat" elif user == 4: filename ="c499testpat.pat" elif user == 5: filename ="c1355testpat.pat" elif user == 6: filename ="c6288testpat.pat" fp = open(filename) |
用python还有别的方法吗
这导致了名称错误:未定义名称"filename"
您可以将文件列表存储为python列表,如下所示:
1 | files = ["filename_1","filename_2","filename_3"] |
然后,要打印它们,您将使用for循环:
1 2 | for i, s in enumerate(files): # Use enumerate because we need to know which element it was print(str(i + 1) +":"+ s) # i + 1 because lists start from 0 |
要确保输入是数字,请使用仅在输入是有效数字时退出的while循环:
1 2 3 4 5 6 7 | while True: inp = input() if inp.isdigit(): filename = files[int(inp) - 1] # - 1 because lists start from 0 break else: print("Enter a number") |
你仍然需要确保这个数字不太大(或者不太小)。
可能是因为您需要先将用户转换为
由于这个问题表明了学习编码的强烈意愿,并且已经尝试了一些东西,所以我提供了一个适用于Python版本3的变体(在版本2中,需要原始输入而不是输入,并且将来需要导入来声明打印函数):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #! /usr/bin/env python3 import sys names_known = ( # Hints 1 and 2 None,"tp.txt","c17testpat.pat","c432test.pat", "c499testpat.pat","c1355testpat.pat","c6288testpat.pat") options_map = dict(zip(range(len(names_known)), names_known)) # 3 print("Enter:") for choice, name in enumerate(names_known[1:], start=1): # 4 print('%d.%s' % (choice, name)) user_choice = input("Enter a number") # 5 try: # 6 entry_index = int(user_choice) except: sys.exit("No integer given!") if not entry_index or entry_index not in options_map: # 7 sys.exit("No filename matching %d" % (entry_index,)) with open(options_map[entry_index]) as f: # 8 # do something with f pass |
许多事情仍然可能出错,任何错误都需要用户重新启动(不包括while循环等),但有些成就
不是python,但值得知道如何通过bash使用它。一个简单的bash示例,列出一个文件夹内容,并让用户根据索引选择文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # menu.sh # usage: bash menu.sh FOLDER select FILENAME in $1/*; do case $FILENAME in "$QUIT") echo"Exiting." break ;; *) echo"You picked $FILENAME ($REPLY)" chmod go-rwx"$FILENAME" ;; esac done |
学分http://tldp.org/ldp/bash-初学者指南/html/sect_09_06.html