FAQ
Hi all, newbie question here. I'm using python 2.7. I've built my first
program to pull some info off the web, process it, and build dialpeers
for a cisco router. I have 2 problems - the first is the formatting of
printing the gathered information to a file. It seems to be inserting a
new line after the variable is written. I've searched the web, but
unsure of which method could fix this issue.

Here is my code snippet:

count=0
o = open('dialpeers.txt', 'w')
for line in open('final.txt', 'r'):
figureDpn = count + 1000
dpn = str(figureDpn)
label = "dial-peer voice " + dpn
o.write(label)
o.write('\n')
destpatt = "destination-pattern " + line + "...."
o.write(destpatt)
o.write('\n')
o.write("description *** local outbound dialpeer ***")
o.write('\n')
port = "port " + p
o.write(port)
o.write('\n')
o.write('\n')
count = count + 1

Output:
dial-peer voice 1000
destination-pattern 252200
....
description *** local outbound dialpeer ***
port 0/1


Desired Output:
dial-peer voice 1000
destination-pattern 252200....
description *** local outbound dialpeer ***
port 0/1


I've just started with Python 3 weeks ago, so my code is poortly
written. I would appreciate any suggestions to improve.

Ed Ellerbee


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110628/6b0d4d71/attachment.html>

Search Discussions

  • Noah Hall at Jun 28, 2011 at 4:18 pm

    On Tue, Jun 28, 2011 at 5:05 PM, Ellerbee, Edward wrote:
    Hi all, newbie question here. I'm using python 2.7. I've built my first
    program to pull some info off the web, process it, and build dialpeers for a
    cisco router. I have 2 problems - the first is the formatting of printing
    the gathered information to a file. It seems to be inserting a new line
    after the variable is written. I've searched the web, but unsure of which
    method could fix this issue.

    Here is my code snippet:

    count=0
    o = open('dialpeers.txt', 'w')
    for line in open('final.txt', 'r'):
    ??? figureDpn = count + 1000
    ??? dpn = str(figureDpn)
    ??? label = "dial-peer voice " + dpn
    ??? o.write(label)
    ??? o.write('\n')
    ??? destpatt = "destination-pattern " + line + "...."
    Try line.rstrip() instead. It'll remove all newlines. Also, I suggest
    you use string formatting, for example,
    destpatt = "destination-pattern %s...." % line.rstrip()
  • Ellerbee, Edward at Jun 28, 2011 at 5:32 pm
    Thank you!

    That works perfect, I'll have to look into string formatting more.

    My next issue to solve I've been researching is:

    How to condense a group of numbers to a wildcard list. For example:

    252205
    252206
    252208
    252220
    252221
    252222
    252223
    919745
    919725
    919785
    704770 thru 704799 (all numbers listed individually in a file)

    Condense to:
    25220[568]
    25222[0-3] (or 25222[0123] is fine too)
    9197[248]5
    7047[0-9][0-9]

    Any recommendations on where to start, a method or function to research?

    Thanks!

    Edward Ellerbee



    -----Original Message-----
    From: Noah Hall [mailto:enalicho at gmail.com]
    Sent: Tuesday, June 28, 2011 12:18 PM
    To: Ellerbee, Edward
    Cc: python-list at python.org
    Subject: Re: Suppressing newline writing to file after variable
    On Tue, Jun 28, 2011 at 5:05 PM, Ellerbee, Edward wrote:
    Hi all, newbie question here. I'm using python 2.7. I've built my
    first program to pull some info off the web, process it, and build
    dialpeers for a cisco router. I have 2 problems - the first is the
    formatting of printing the gathered information to a file. It seems to
    be inserting a new line after the variable is written. I've searched
    the web, but unsure of which method could fix this issue.

    Here is my code snippet:

    count=0
    o = open('dialpeers.txt', 'w')
    for line in open('final.txt', 'r'):
    ??? figureDpn = count + 1000
    ??? dpn = str(figureDpn)
    ??? label = "dial-peer voice " + dpn
    ??? o.write(label)
    ??? o.write('\n')
    ??? destpatt = "destination-pattern " + line + "...."
    Try line.rstrip() instead. It'll remove all newlines. Also, I suggest you use string formatting, for example,
    destpatt = "destination-pattern %s...." % line.rstrip()
  • Noah Hall at Jun 28, 2011 at 7:27 pm

    On Tue, Jun 28, 2011 at 6:32 PM, Ellerbee, Edward wrote:
    Thank you!

    That works perfect, I'll have to look into string formatting more.

    My next issue to solve I've been researching is:

    How to condense a group of numbers to a wildcard list. For example:

    252205
    252206
    252208
    252220
    252221
    252222
    252223
    919745
    919725
    919785
    704770 thru 704799 (all numbers listed individually in a file)

    Condense to:
    25220[568]
    25222[0-3] (or 25222[0123] is fine too)
    9197[248]5
    7047[0-9][0-9]

    Any recommendations on where to start, a method or function to research?
    Hm, perhaps re (http://docs.python.org/library/re.html). It depends on
    whether it's a standard static set of values you need to compare
    against, or a undefined dynamic set.
  • Chris Angelico at Jun 28, 2011 at 10:56 pm

    On Wed, Jun 29, 2011 at 3:32 AM, Ellerbee, Edward wrote:
    How to condense a group of numbers to a wildcard list. For example:

    252205
    252206
    252208

    Condense to:
    25220[568]
    Assuming you have the list sorted (if not, that's the first place to
    start), I'd do a six-pass approach - one pass for each digit. It's
    simple and readable, and I doubt you'll be working with enough numbers
    for its inefficiency to be a problem. Something like this (untested
    code):

    lastprefix=tails=None
    for cur in list_of_numbers:
    prefix=cur[:5]; tail=cur[5]
    if prefix!=lastprefix:
    if lastprefix!=None:
    if len(tails)>1: emit("%s[%s]"%(lastprefix,tails))
    else emit(lastprefix+tails)
    lastprefix,tails=prefix,""
    tails+=tail
    if lastprefix!=None:
    if len(tails)>1: emit("%s[%s]"%(lastprefix,tails))
    else emit(lastprefix+tails)

    Feed the emitted results from this pass into the next pass, in which
    prefix is cur[:4] and tail is cur[4], etc. For the subsequent passes,
    you'll also need to worry about a suffix (which would be cur[5:] when
    you're looking at cur[4]), and ensure that that matches, same as the
    prefix.

    This is completely untested, but it should be a start. (Replace the
    calls to the imaginary "emit" function with whatever you do to emit
    results - for the intermediate passes, that's probably appending to a
    list.)

    Chris Angelico
  • Chris Angelico at Jun 28, 2011 at 10:59 pm

    On Wed, Jun 29, 2011 at 8:56 AM, Chris Angelico wrote:
    ? ? ?else emit(lastprefix+tails)
    ?else emit(lastprefix+tails)
    Typo in the above code. The else needs a colon after it, both times.

    ChrisA
  • Chris Angelico at Jul 14, 2011 at 2:38 pm

    On Fri, Jul 15, 2011 at 12:04 AM, Ellerbee, Edward wrote:
    Hey Chris,

    I was reading over this again, trying to understand the logic (I'm a
    n00b)

    Could you explain this a bit? I'd like to build this emit function, but
    I still don't have a firm grasp on functions. All of my code is line by
    line. I'll convert it as a learn more.
    I'm responding on-list as I believe others will wish to weigh in (if
    only to point out some improvements to my code - it's hastily put
    together). Caution, post is long.

    Defining functions in Python is, broadly speaking, just a matter of
    collecting up a bunch of statements and giving it a name. Compare:

    if x>5:
    do_this()
    do_that()
    etc()

    with:

    def abcde():
    do_this()
    do_that()
    etc()

    The first one does the three statements, in order, if and only if the
    condition is true. The second one gives a name to those three
    statements, so you can use it as a new statement:

    abcde()

    It'll do the same three things, every time you call it. It's
    effectively the same as putting the function's body in where you call
    it (that's an extremely sloppy explanation, but near enough).
    So, I'd want this to go after the sort step, and before the format step.
    I can figure that piece out, just trying to get this little block of
    code to work.
    Yes, that would be the place to put it.

    Here's a reworked version that you can test in IDLE:


    def combine(list_of_numbers, position):
    lastprefix=tails=lastsuffix=None
    result=[]
    for cur in list_of_numbers:
    prefix=cur[:position]; tail=cur[position]; suffix=cur[position+1:]
    if prefix!=lastprefix or suffix!=lastsuffix:
    if lastprefix!=None:
    if len(tails)>1: result.append("%s[%s]%s"%(lastprefix,tails,lastsuffix))
    else: result.append(lastprefix+tails+lastsuffix)
    lastprefix,tails,lastsuffix=prefix,"",suffix
    tails+=tail
    if lastprefix!=None:
    if len(tails)>1: result.append("%s[%s]%s"%(lastprefix,tails,lastsuffix))
    else: result.append(lastprefix+tails+lastsuffix)
    return result

    It incorporates some of the enhancements I mentioned in the original post.
    combine(['252205','252206','252208'],5)
    ['25220[568]']
    combine(['252205','252215','252225'],4)
    ['2522[012]5']

    Notice that the 'emit' function is now 'result.append()' - it builds
    up a list to return. You can now chain the calls; start with a list of
    numbers and then call combine() in a loop.

    # List of numbers from your previous post
    numbers = ['252205', '252206', '252208', '252220', '252221', '252222',
    '252223', '919745', '919725', '919785', '704770', '704771', '704772',
    '704773', '704774', '704775', '704776', '704777', '704778', '704779',
    '704780', '704781', '704782', '704783', '704784', '704785', '704786',
    '704787', '704788', '704789', '704790', '704791', '704792', '704793',
    '704794', '704795', '704796', '704797', '704798', '704799']


    numbers = combine(numbers,5)

    numbers = combine(numbers,4)

    numbers = combine(numbers,3)

    numbers = combine(numbers,2)

    numbers = combine(numbers,1)

    numbers = combine(numbers,0)

    If you do these statements one at a time in IDLE and inspect the
    'numbers' list each time, you'll see the combinations sorting
    themselves out. (With this starting list, only the first two will have
    any effect.)

    The last set of calls can be turned into a for loop:
    for pos in range(5,-1,-1):
    numbers = combine(numbers,pos)

    In fact, you could actually take it out of being a function, if you wanted to:

    list_of_numbers = ['252205', '252206', '252208', '252220', '252221',
    '252222', '252223', '919745', '919725', '919785', '704770', '704771',
    '704772', '704773', '704774', '704775', '704776', '704777', '704778',
    '704779', '704780', '704781', '704782', '704783', '704784', '704785',
    '704786', '704787', '704788', '704789', '704790', '704791', '704792',
    '704793', '704794', '704795', '704796', '704797', '704798', '704799']

    for position in range(5,-1,-1):
    lastprefix=tails=lastsuffix=None
    result=[]
    for cur in list_of_numbers:
    prefix=cur[:position]; tail=cur[position]; suffix=cur[position+1:]
    if prefix!=lastprefix or suffix!=lastsuffix:
    if lastprefix!=None:
    if len(tails)>1: result.append("%s[%s]%s"%(lastprefix,tails,lastsuffix))
    else: result.append(lastprefix+tails+lastsuffix)
    lastprefix,tails,lastsuffix=prefix,"",suffix
    tails+=tail
    if lastprefix!=None:
    if len(tails)>1: result.append("%s[%s]%s"%(lastprefix,tails,lastsuffix))
    else: result.append(lastprefix+tails+lastsuffix)
    list_of_numbers = result

    That's what the function definition does - it takes a block of code
    and gives it a new name. (There's a lot more to it than that, thank
    you pedants I know, but in this simple example that's what it's
    doing.)

    Hope that's of use!

    Chris Angelico
  • Ellerbee, Edward at Jul 14, 2011 at 2:53 pm
    Holy cow, that's perfect!

    Thanks so much :)

    Would it be alright if I post my code on the list for critiquing? I'm
    learning python to supplement my voice engineering position - time
    consuming tasks that can be automated will take less time.


    Edward Ellerbee


    -----Original Message-----
    From: python-list-bounces+eellerbee=bbandt.com at python.org
    [mailto:python-list-bounces+eellerbee=bbandt.com at python.org] On Behalf
    Of Chris Angelico
    Sent: Thursday, July 14, 2011 10:39 AM
    To: python-list at python.org
    Subject: Re: Suppressing newline writing to file after variable

    On Fri, Jul 15, 2011 at 12:04 AM, Ellerbee, Edward
    wrote:
    Hey Chris,

    I was reading over this again, trying to understand the logic (I'm a
    n00b)

    Could you explain this a bit? I'd like to build this emit function,
    but I still don't have a firm grasp on functions. All of my code is
    line by line. I'll convert it as a learn more.
    I'm responding on-list as I believe others will wish to weigh in (if
    only to point out some improvements to my code - it's hastily put
    together). Caution, post is long.

    Defining functions in Python is, broadly speaking, just a matter of
    collecting up a bunch of statements and giving it a name. Compare:

    if x>5:
    do_this()
    do_that()
    etc()

    with:

    def abcde():
    do_this()
    do_that()
    etc()

    The first one does the three statements, in order, if and only if the
    condition is true. The second one gives a name to those three
    statements, so you can use it as a new statement:

    abcde()

    It'll do the same three things, every time you call it. It's effectively
    the same as putting the function's body in where you call it (that's an
    extremely sloppy explanation, but near enough).
    So, I'd want this to go after the sort step, and before the format step.
    I can figure that piece out, just trying to get this little block of
    code to work.
    Yes, that would be the place to put it.

    Here's a reworked version that you can test in IDLE:


    def combine(list_of_numbers, position):
    lastprefix=tails=lastsuffix=None
    result=[]
    for cur in list_of_numbers:
    prefix=cur[:position]; tail=cur[position]; suffix=cur[position+1:]
    if prefix!=lastprefix or suffix!=lastsuffix:
    if lastprefix!=None:
    if len(tails)>1:
    result.append("%s[%s]%s"%(lastprefix,tails,lastsuffix))
    else: result.append(lastprefix+tails+lastsuffix)
    lastprefix,tails,lastsuffix=prefix,"",suffix
    tails+=tail
    if lastprefix!=None:
    if len(tails)>1:
    result.append("%s[%s]%s"%(lastprefix,tails,lastsuffix))
    else: result.append(lastprefix+tails+lastsuffix)
    return result

    It incorporates some of the enhancements I mentioned in the original
    post.
    combine(['252205','252206','252208'],5)
    ['25220[568]']
    combine(['252205','252215','252225'],4)
    ['2522[012]5']

    Notice that the 'emit' function is now 'result.append()' - it builds up
    a list to return. You can now chain the calls; start with a list of
    numbers and then call combine() in a loop.

    # List of numbers from your previous post numbers = ['252205', '252206',
    '252208', '252220', '252221', '252222', '252223', '919745', '919725',
    '919785', '704770', '704771', '704772', '704773', '704774', '704775',
    '704776', '704777', '704778', '704779', '704780', '704781', '704782',
    '704783', '704784', '704785', '704786', '704787', '704788', '704789',
    '704790', '704791', '704792', '704793', '704794', '704795', '704796',
    '704797', '704798', '704799']


    numbers = combine(numbers,5)

    numbers = combine(numbers,4)

    numbers = combine(numbers,3)

    numbers = combine(numbers,2)

    numbers = combine(numbers,1)

    numbers = combine(numbers,0)

    If you do these statements one at a time in IDLE and inspect the
    'numbers' list each time, you'll see the combinations sorting themselves
    out. (With this starting list, only the first two will have any effect.)

    The last set of calls can be turned into a for loop:
    for pos in range(5,-1,-1):
    numbers = combine(numbers,pos)

    In fact, you could actually take it out of being a function, if you
    wanted to:

    list_of_numbers = ['252205', '252206', '252208', '252220', '252221',
    '252222', '252223', '919745', '919725', '919785', '704770', '704771',
    '704772', '704773', '704774', '704775', '704776', '704777', '704778',
    '704779', '704780', '704781', '704782', '704783', '704784', '704785',
    '704786', '704787', '704788', '704789', '704790', '704791', '704792',
    '704793', '704794', '704795', '704796', '704797', '704798', '704799']

    for position in range(5,-1,-1):
    lastprefix=tails=lastsuffix=None
    result=[]
    for cur in list_of_numbers:
    prefix=cur[:position]; tail=cur[position]; suffix=cur[position+1:]
    if prefix!=lastprefix or suffix!=lastsuffix:
    if lastprefix!=None:
    if len(tails)>1:
    result.append("%s[%s]%s"%(lastprefix,tails,lastsuffix))
    else: result.append(lastprefix+tails+lastsuffix)
    lastprefix,tails,lastsuffix=prefix,"",suffix
    tails+=tail
    if lastprefix!=None:
    if len(tails)>1:
    result.append("%s[%s]%s"%(lastprefix,tails,lastsuffix))
    else: result.append(lastprefix+tails+lastsuffix)
    list_of_numbers = result

    That's what the function definition does - it takes a block of code and
    gives it a new name. (There's a lot more to it than that, thank you
    pedants I know, but in this simple example that's what it's
    doing.)

    Hope that's of use!

    Chris Angelico
  • Chris Angelico at Jul 14, 2011 at 3:03 pm

    On Fri, Jul 15, 2011 at 12:53 AM, Ellerbee, Edward wrote:
    Holy cow, that's perfect!

    Thanks so much :)

    Would it be alright if I post my code on the list for critiquing? I'm
    learning python to supplement my voice engineering position - time
    consuming tasks that can be automated will take less time.
    If it's not too long, sure! If it's more than can conveniently be
    read, post it on one of those code-sharing places like
    http://pastebin.com/ and post a link; then those who want to read it
    can do so, and those who would rather avoid it have that option too.

    ChrisA

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedJun 28, '11 at 4:05p
activeJul 14, '11 at 3:03p
posts9
users3
websitepython.org

People

Translate

site design / logo © 2023 Grokbase