Any algorithm to preserve whitespaces?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jan 23 19:49:59 EST 2013


Santosh Kumar wrote:

> Yes, Peter got it right.

Peter? Which Peter? What's "it" that he got right?

You have deleted all context from your post, so I have no idea what you are
talking about. And whatever program you are using to post is stripping out
threading information, so I can't tell what post you are replying to.

Please take careful note of the posting conventions used by the experienced
regulars on this forum, and copy their style. That is for your benefit as
well as ours.


> Now, how can I replace:
> 
>     script, givenfile = argv
> 
> with something better that takes argv[1] as input file as well as
> reads input from stdin.
> 
> By input from stdin, I mean that currently when I do `cat foo.txt |
> capitalizr` it throws a ValueError error:
> 
>     Traceback (most recent call last):
>       File "/home/santosh/bin/capitalizr", line 16, in <module>
>         script, givenfile = argv
>     ValueError: need more than 1 value to unpack
> 
> I want both input methods.

The usual convention in Unix and Linux is that if the file name is "-", read
from stdin instead. Something like this, untested:


givenfile = sys.argv[1]
if givenfile == '-':
    data = sys.stdin.read()
else:
    data = open(givenfile).read()


Adding error checking etc. is left as an exercise.




-- 
Steven




More information about the Python-list mailing list