Search code examples
pythonfileraw-input

python use raw_input for range filenames


Currently I've got a script that consumes text filename (for example 1.txt) from raw input, opens it and then parses it for my needs:

fname = raw_input("Enter file name: ")
fh = open(str(fname))
...

There are 10 files in the directory: 1.txt, 2.txt, ... 10.txt

So how can I input range filenames in raw input like from 2.txt to 6.txt and parse these files 1 by 1. Instead of running script every time for a single file?


Solution

  • I will assume that the file names are n.txt where n >= 1
    then,

    def parse(flie):
        pass
        # this is where you parse the file.
    
    lower = raw_input("Enter start: ") # assume int
    upper = raw_input("Enter end: ") # assume int and >= lower
    files = [str(i)+'.txt' for i in range(int(lower),int(upper)+1)]
    
    for file in files:
        parse(file)