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
  • 21,295
  • 1
  • 48
  • 66
bard
  • 2,762
  • 9
  • 35
  • 49

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
  • 109,961
  • 14
  • 137
  • 171
3

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

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306