Search code examples
pythonshellinputcat

"Index out of range" while reading contents from a file through cat PYTHON


I am trying to get input from a file, through cat command, into a python file. My python version is 3.5. The code looks like this.

with open(sys.argv[1]) as f:
    while True:
        if f.readline()== '':
            break
        line = f.readline().strip()

And i am getting the input through the following command.

python cptest.py | cat ts.csv

But i keep running into the following error.

File "cptest.py", line 9, in with open(sys.argv[1]) as f: IndexError: list index out of range

How can i send input to a python script from a file using cat command? I have to use cat command, or any other way i can pipe the input to the file.


Solution

  • It looks like it is your command is the issue here. You are piping the output from your python script to cat and also use cat to open a file which means cat will ignore whatever you pipe to it. You should pipe the output of cat to your script instead: cat ts.csv | python cptest.py Then, in order to read input from the standard input in python (from the pipe) you should do it like this: for line in sys.stdin. I would lite to suggest the alternative of providing the filename to your python script as an argument like so: python cptest.py ts.csv and then open this file (you find this name in sys.argv[1] in python (and not with cat) and loop through it line by line.

    Good luck, Teo