7

I am trying to read the content of a text file that was redirected stdin via the command line, and send it by the Internet when the receiver has to assemble it back to it's original form.

For instance:

$ python test.py < file.txt

I have tried to read the file and to assemble it back with the following code inspired by link:

for line in sys.stdin:
  stripped = line.strip()
  if not stripped: break
  result = result + stripped

print "File is beeing copied"
file = open("testResult.txt", "w")
file.write(result)
file.close()
print "File copying is complete!"

But this solution works as long as I DON'T have an empty row( two '\n' one after another) in my file,if i do have, my loop breaks and the File reading ends.How can I read from stdin till i reach <> of the file that was redirected?

2
  • 1
    file.write(sys.stdin.read()) Commented Dec 5, 2014 at 15:03
  • For anyone else as silly as me, before you go down the SO rabbit hole, make sure your terminal is in the same directory as the .txt file (or it'll run an empty file). Commented Nov 28, 2021 at 18:42

3 Answers 3

10

Why are you even looking at the data:

result = sys.stdin.read()
Sign up to request clarification or add additional context in comments.

Comments

4

Instead of breaking, you just want to continue to the next line. The iterator will stop automatically when it reaches the end of the file.

import sys
result = ""
for line in sys.stdin:
    stripped = line.strip()
    if not stripped:
        continue
    result += stripped

Comments

2

line.strip() is removing the trailing newline from the read line.

If you want that newline then you shouldn't need to do that I don't think (does your output file have the input newlines)?

That if stripped bit is looking for a blank line and was, in the original, the termination characteristic of the loop.

That isn't your termination marker though. You don't want to stop there. So don't.

The loop will finish on its own when sys.stdin reaches the end of the input (EOF).

Drop line.strip() drop if not stripped: break replace result = result + stripped with result = result + line and then write that to the file to get a simple (though likely expensive) cp script.

There are likely more efficient ways to read all the lines from standard input if you want to do something with them though (depending on your goal).

1 Comment

Yes you are right, I the stripping is unneeded (because it changes the text it read, and this is not my goal). And indeed "William Pursell" suggest a more "efficient way to do this".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.