0

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.

Joel Niemelä
  • 168
  • 1
  • 3
  • 13
  • Possible duplicate of [How to pipe input to python line by line from linux program?](https://stackoverflow.com/questions/17658512/how-to-pipe-input-to-python-line-by-line-from-linux-program) – 0TTT0 Oct 20 '17 at 01:40
  • @OTTTO I don't think so, however, I'll take a look at it just to make sure :) thx – Joel Niemelä Oct 20 '17 at 02:09
  • 1
    If you log `repr(tmp)`, the difference (between the inputs -- ie. exactly how your file *contains different data* than what you're entering at the keyboard) will be obvious. – Charles Duffy Oct 20 '17 at 02:50
  • @CharlesDuffy Ok, I'll take a look at that, thx! – Joel Niemelä Oct 20 '17 at 03:08
  • @CharlesDuffy Thanks! My problem was that my file had a \r at the end of each line, so I did some quick googling and found out that I have to use `.rstrip()` to remove it :) – Joel Niemelä Oct 20 '17 at 03:14

1 Answers1

2

It is a carriage-return and line-feed thing, but you have not provided enough clues to determine the exact problem.

Experiment by adding the following to the end of your strings before using them in a print statement. +'\r' +'\n'

Inspect your files with a hex editor after reading https://blog.codinghorror.com/the-great-newline-schism/.

Check how your console, aka terminal window, aka command line, is configured to handle these control characters. Are you using the default settings?

You must consistently use these control characters, as per the conventions of your operating system.

It would complicate matters further if you are using telnet or ssh on for example a Microsoft operating system to run code on for example a Unix computer.