Re: Any algorithm to preserve whitespaces?

Discussion in 'Python' started by Peter Otten, Jan 23, 2013.

  1. Peter Otten

    Peter Otten Guest

    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()
    Peter Otten, Jan 23, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Santosh Kumar

    Any algorithm to preserve whitespaces?

    Santosh Kumar, Jan 19, 2013, in forum: Python
    Replies:
    0
    Views:
    123
    Santosh Kumar
    Jan 19, 2013
  2. Lie Ryan
    Replies:
    0
    Views:
    122
    Lie Ryan
    Jan 19, 2013
  3. Mitya Sirenef

    Re: Any algorithm to preserve whitespaces?

    Mitya Sirenef, Jan 19, 2013, in forum: Python
    Replies:
    0
    Views:
    130
    Mitya Sirenef
    Jan 19, 2013
  4. Santosh Kumar

    Re: Any algorithm to preserve whitespaces?

    Santosh Kumar, Jan 23, 2013, in forum: Python
    Replies:
    0
    Views:
    89
    Santosh Kumar
    Jan 23, 2013
  5. Peter Otten
    Replies:
    0
    Views:
    84
    Peter Otten
    Jan 23, 2013
Loading...

Share This Page