TAGS :Viewed: 7 - Published at: a few seconds ago

[ Open file from keyboard in Python ]

I want to run a script over a .txt file in a given directory. Files in the folder will change and I'm interested in listing them and picking one via keyboard entry.

This is the code I have so far,

    import os    
    folder = os.getcwd() #Current directory
    files = [f for f in os.listdir(folder) if f.endswith('.txt')]
    print 'Files available:\n %r' % files

Which would give me an output with the list of files that I could analyze.

Sth like this,

Files available: ['File.txt', 'Foo.txt', 'Test.txt']

And now the piece of code in which I'm stuck:

    while True:
        print "Introduce the name of the file" 
        choice = raw_input()
        if choice.lower() == 'FILE FROM THE LIST':#Here's where I'm stuck
            with open('FILE FROM THE LIST', 'rt') as inputfile:
            data = csv.reader(inputfile)
            #Do stuff
        elif choice.lower() == 'e':
            print "Please, choose a valid option or type 'e' to exit"

What should I do to type the name of the file and running the script from there?
Ideally I would like to create a link between the listed files and a key or a number to make it shorter, e.g.

[Type '1' to open File.txt,
Type '2' to open Foo.txt,
Type '3' to open 'Text.txt',...]

But typing the name would be a nice way to begin for me.

Answer 1

It appears you are looking for the in keyword. Then you could check for something like

if choice in files:
    #Do whatever you want with that filename

Or you might consider first generating a dictionary with keys for input from the filenames. For example:

for count,entry in enumerate(files):

And then check your input:

if choice in my_key_dict:

Of course you would then also want to generate your listing for the user from my_key_dict in some way.

Answer 2

Here's a simple solution to your problem:

import glob

files = glob.glob("*.txt")
print "select file:"
for index, filename in enumerate(files):
   print index, filename

print "enter number of file to work on:",
number = int(raw_input())

print "working on file: ", files[number]

Please note how I am using the "glob" module as a simpler means of matching the Txt files instead of looping and matching. I did omit error handling for the user input that is automatically cast to an integer via the int() function. Finally, the numbers now start at zero. If you want them to start at one, you can just add 1 when displaying them and subtract 1 from the user input.