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?
Why are you even looking at the data:
result = sys.stdin.read()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With