-1

How to open a file from the list of given files based on the user's input which is an integer

print("Enter 1.tp.txt\n2.c17testpat.pat\n3.c432testpat.pat\n4.c499testpat.pat\n5.c1335testpat.pat\n6.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)

is there any other way to do it in python

this caused NameError: name 'filename' is not defined

Dilettant
  • 3,267
  • 3
  • 29
  • 29
Abishek Kumaresan
  • 107
  • 1
  • 4
  • 15
  • 1
    What you have read is a string and it will not be equal to any of the things you compare it against, so the variable `filename` will not exist. Convert it to an int and output some error message if you do not receive valid input. – Paul Rooney Jul 07 '16 at 12:51
  • http://stackoverflow.com/questions/11479816/what-is-the-python-equivalent-for-a-case-switch-statement might help – Deca Jul 07 '16 at 12:58

4 Answers4

3

You could store the file list as a Python list, like so:

files = ["filename_1", "filename_2", "filename_3"]

Then to print them, you would use a for loop:

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

To make sure your input is a number, use a while loop that exits only if the input is a valid number:

while True:
    inp = input()
    if inp.isdigit():
        filename = files[int(inp) - 1] # - 1 because lists start from 0
        break
    else:
        print("Enter a number")

You'll still need to make sure the number is not too big (or small, for that matter).

randomdude999
  • 701
  • 7
  • 20
1

probably because you need to convert user to int first (might be a string as written). Also you should probably finish with a default case to throw an error if the user inputs a non sensical value...

Julien
  • 13,986
  • 5
  • 29
  • 53
0

Not python but worth to know how to use it via bash. A simple bash sample that list a folder content and let's user choose the file by the index.

# 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

Credit http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_06.html

Ali SAID OMAR
  • 6,404
  • 8
  • 39
  • 56
0

As the question indicates a strong will to learn coding and already tried something, I offer a variant that works for python version 3 (in version 2 one would need raw_input instead of input and a future import to declare the print function):

#! /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

Many things still can go wrong, and any error will need the user to restart (no while loops etc.), but some achievements

  1. Have the names only stored once (here I picked a tuple)
  2. Keep the 1 as first number in user interface (insert dummy at index 0)
  3. Derive a dict from the tuple storing the names (dict offers fast lookup)
  4. Build the user interface info from the name tuple (ignoring the dummy)
  5. Separate input from validation
  6. Check domain type first (integer). If fails exit early via sys.exit and give info
  7. Check domain membership otherwise exit with info
  8. open the resource filename targets in a context block so you do not forget to close when done with the processing
Dilettant
  • 3,267
  • 3
  • 29
  • 29