Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: Any algorithm to preserve whitespaces? (http://www.velocityreviews.com/forums/t956852-re-any-algorithm-to-preserve-whitespaces.html)

Peter Otten 01-23-2013 10:04 PM

Re: Any algorithm to preserve whitespaces?
 
Santosh Kumar wrote:

> Yes, Peter got it right.
>
> 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.


You can use argparse and its FileType:

import argparse
import sys

parser = argparse.ArgumentParser()
parser.add_argument("infile", type=argparse.FileType("r"), nargs="?",
default=sys.stdin)
args = parser.parse_args()

for line in args.infile:
print line.strip().title() # replace with your code


As this has the small disadvantage that infile is opened immediately I tend
to use a slight variation:

import argparse
import sys
from contextlib import contextmanager

@contextmanager
def xopen(filename):
if filename is None or filename == "-":
yield sys.stdin
else:
with open(filename) as instream:
yield instream

parser = argparse.ArgumentParser()
parser.add_argument("infile", nargs="?")
args = parser.parse_args()

with xopen(args.infile) as instream:
for line in instream:
print line.strip().title()





All times are GMT. The time now is 09:55 PM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57