0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect for what I want. Thank you very much.
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:

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.

2 Comments

Thanks for the answer, the thing is that the idea of assigning a key to each and every of the files seems to be a nice one in case you don't have too many in the list. Just in case I end up working with hundreds of them - which is possible -, I prefer to generate them dinamically, as ofrommel has proposed in his solution.
I don't think that the general interface idea scales well to hundreds of files. In that case I would rather have my user provide the list of files to process via the command line. Or by a file selection widget if you are working with a GUI. But I agree that ofrommel's solution is much nicer before that point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.