Search code examples
pythonstdinpython-2.x

Reading text file using sys.stdin


I have a simple program:

import sys
import string

stopWordsPath = sys.argv[1]
delimitersPath = sys.argv[2]
stopWordsList = []
delimiterList = []

with open(stopWordsPath) as f:
    for line in f:
        line = line.strip()
        stopWordsList.append(line)

with open(delimitersPath) as f:
delimiterList = f.read().strip()

for line in sys.stdin:
    print line

When I try to do something like this in linux:

python TitleCountMapper.py stopwords.txt delimiters.txt | input.txt

It keeps hanging on me. I'm using stdin because it's the way the input is required. Is this the right way to pass the txt file so it can be read by stdin?


Solution

  • | means to direct the output of the preceding program as an input to the program that follows, rather than providing input from the file that follows to the program that precedes it.

    You should use < instead of |:

    python TitleCountMapper.py stopwords.txt delimiters.txt < input.txt