Why does syntax "main.py < input.txt" not working

Viewed 216

Using the command line, my program would take a .txt input.

The syntax my prof show to do this is:

python main.py < input.txt

but I get the error IndexError: list index out of range

The code I used to open files:

import.sys

if len(sys.argv[1]) <= 0:
        print("Please input a file path")
        exit(-1)

    with open(sys.argv[1], 'r') as input_file:
        # loops to create new "arg" array for every new line
        for line in input_file.readlines():

How can I fix this?

3 Answers

python main.py < input.txt will pipe the contents of "input.txt" to stdin on the Python process, you can read this piped content via sys.stdin

import sys

for line in sys.stdin:
    print(line)

Omit the < to pass it as an argument.

python main.py input.txt

main.py:

import sys

if len(sys.argv[1]) <= 0:
    print("Please input a file path")
    exit(-1)

with open(sys.argv[1], 'r') as input_file:
    for line in input_file.readlines():
        pass

you have only passed one argument to your main.py which is the "input.txt" so change sys.argv[1] to sys.argv[0]

Related