I'm having trouble reading input from a .txt file within a python program due to some weird behavior in my code. I'm running my python script like this:
python3 file.py < input.txt
My python file (file.py
) looks like this:
inDATA = ''
for i in range(7):
tmp = str(input())
print(tmp)
inDATA = "X" + inDATA + tmp
print(inDATA)
print(inDATA)
My input file (input.txt
) is as follows:
1
2
3
4
5
6
7
When I run python3 file.py
and type in the input (1\n2\n3...) from the console, I get the expected output:
1
X1
2
XX12
3
XXX123
4
XXXX1234
5
XXXXX12345
6
XXXXXX123456
7
XXXXXXX1234567
XXXXXXX1234567
However, when I run python3 file.py < input.txt
I get:
1
X1
2
2X1
3
3XX1
4
4XXX1
5
5XXXX1
6
6XXXXX1
7
7XXXXXX1
7XXXXXX1
Does anyone know what's causing this behavior?
I also tried to run this in python2 with python file.py < input.txt
(and changing input() to raw_input()) but it had no effect.
Edit: This question is not a duplicate of "How to pipe input to python line by line from linux program?", that question asked about How to pipe, this question, on the other hand, is about Why the code acted weird when piping from a file.