2

I have an input file ("abc.in") which I will like to read each line as input(), exactly like how it works on hackerrank and other online coding platforms.

I have seen solutions replicating the same functionality by piping, fileinput and sys etc. On hackerrank I can just use input() to store one line of the input file as a variable. How do I do that locally? Do I store the files in the same place, what command do I use to run this in the terminal?

I thought this would be easy, but somehow I can't seem to figure out how to do it after trying for some time. Apologies if the answer was obvious.

Any help provided is greatly appreciated!

Community
  • 1
  • 1
Poh Zi How
  • 1,489
  • 3
  • 16
  • 38

1 Answers1

5

You can redirect the stdin with < on command line. Let's say you have following input stored to file data.in:

line1
line2

And you have following code stored to test.py:

print(1, input())
print(2, input())

Then you can run the script with redirected stdin:

~$ python3 test.py < data.in
1 line1
2 line2

If you want to save the output to a file you can redirect stdout as well:

~$ python3 test.py < data.in > data.out
niemmi
  • 17,113
  • 7
  • 35
  • 42
  • Thank you! I am new to HackerRank and new to using inputs in the way HackerRank uses them for Python. You've saved me a lot of time in trying to figure this out! – allardbrain Aug 07 '17 at 03:32