Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #37510
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: Any algorithm to preserve whitespaces? |
| Date | 2013-01-23 23:04 +0100 |
| Organization | None |
| References | <CAE7MaQZyvwOvD6ggMDZ4+b=r1PsKuYX+VZThEpKvxBbfJJCK3g@mail.gmail.com> <50FAEE23.5030107@lightbird.net> <CAE7MaQb2-qQXuAJ4jK6RB+fOPO0ZjK6_gEuigqP_FOn0=Sv29g@mail.gmail.com> <50FFBCC5.5020506@davea.name> <CAE7MaQbgpj+xsELBEkmHq1GS9-cRNph+O-sq=5oPh4QTt=2Z=g@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.924.1358979213.2939.python-list@python.org> (permalink) |
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()
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Any algorithm to preserve whitespaces? Peter Otten <__peter__@web.de> - 2013-01-23 23:04 +0100
csiph-web