Informatico_Sano
Informatico_Sano

Reputation: 215

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':
            break
        else:
            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.

Upvotes: 0

Views: 967

Answers (2)

ofrommel
ofrommel

Reputation: 2177

Here's a simple solution to your problem:

import glob

files = glob.glob("*.txt")
files.sort()
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.

Upvotes: 1

Christoph
Christoph

Reputation: 1557

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:

my_key_dict={}
for count,entry in enumerate(files):
    my_key_dict[count]=entry

And then check your input:

if choice in my_key_dict:
    filename=my_key_dict[choice]

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

Upvotes: 1

Related Questions