0

I have a program that takes an input file:

python subprogram.py < input.txt > out.txt

If I have a number of input files, how can I write a single python program runs on those inputs and produces a single output? I believe the program should run like:

python program.py < input_1.txt input_2.txt > out.txt 

And the program itself should look something like:

from subprogram import MyClass
import sys

if __name__ == '__main__':
    myclass = MyClass()
    myclass.run()
1
  • There's a concept error in your shell scripting, < and > modifiers can have one file specified only, not a list of files. Commented Sep 28, 2013 at 21:50

3 Answers 3

5

Have a look at the fileinput module

import fileinput
for line in fileinput.input():
    process(line)

This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed.

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

Comments

3

Make your program accept command line parameters:

python program.py input_1.txt input_2.txt > out.txt 

And you can access them like:

from subprogram import MyClass
import sys

if __name__ == '__main__':
    class = MyClass()
    class.run(sys.argv)

The way you're using is not about Python, it's about your shell. You are just redirect standart input/output to files. If you want to achieve that:

cat input1.txt input2.txt | python subprogram.py > out.txt

1 Comment

Or on the Windows platform: type input_1.txt input_2.txt | python program.py > out.txt
2

Let your shell do the work for you:

cat input_1.txt input_2.txt | python program.py > out.text

The cat command will concatenate the two input files together and your python program can just read from stdin and treat them like one big file.

Comments

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.