0

I have written a program that calculates the counts of each word in an input file. At the moment I am getting the filename using sys.argv[1], but I am actually supposed to be using

python word_counts.py < homer.txt > homer.test

I think homer.txt is the input file that is directed to my python script, while homer.test is the file that the output of my script is written to.

How do I make these work in my program?

JAL
  • 20,877
  • 1
  • 46
  • 65
bard
  • 2,592
  • 6
  • 31
  • 45

2 Answers2

3

The information in homer.txt is provided on standard-in. In python, that is a file handle called sys.stdin:

import sys
for line in sys.stdin: # reads from homer.txt
    # process line
    print(output) # writes to homer.test

homer.test is collecting data from standard-out. In python, the print statement writes to stdout by default. If you want to treat it explicitly as a file handle, you can use sys.stdout.

John1024
  • 103,964
  • 12
  • 124
  • 155
3

Use sys.stdin to read from homer.txt and sys.stdout (or print) to write to homer.test.

Andrew Clark
  • 192,132
  • 30
  • 260
  • 294