-1

I have a text file containing 100s of comma separated IPs with just spaces between them.

I need to take them 10 at a time and put them in another block of code. So, for IPs:

1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, ... 123.123.123.123, 124.124.124.124, 125.125.125.125

I would need:

codethings [1.1.1.1, 2.2.2.2, ... 10.10.10.10] code code code
codethings [11.11.11.11, 12.12.12.12, ... 20.20.20.20] code code code
codethings [21.21.21.21, 22.22.22.22, ... 30.30.30.30] code code code

etc

I'm pretty sure I could do it with RegEx but I can't help but think there are simpler ways to do it.

Any and all help appreciated. Thank you!

rmp5s
  • 17
  • 4

1 Answers1

0

Split on comma, strip excessive whitespace from each element:

txt = '''1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, 
    123.123.123.123, 124.124.124.124, 125.125.125.125'''

ip_list = map(str.strip, txt.split(','))

As for pagination, see answers for: Paging python lists in slices of 4 items OR Is this how you paginate, or is there a better algorithm?

I would also advise (just to be sure) to filter out invalid IP adresses, for example using a generator and socket module:

from __future__ import print_function
import sys
import socket

txt = '''1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, 
    123.123.123.123, 124.124.124, 555.125.125.125,'''

def iter_ips(txt):
    for address in txt.split(','):
        address = address.strip()
        try:
            _ = socket.inet_aton(address)
            yield address
        except socket.error as err:
            print("invalid IP:", repr(address), file=sys.stderr)

print(list(iter_ips(txt)))
Community
  • 1
  • 1
m.wasowski
  • 6,329
  • 1
  • 23
  • 30
  • Would it be possible to use the text file itself instead of putting the IPs directly in the script? (I can't try it at the moment but I'm curious...) Instead of `txt = '''1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, 123.123.123.123, 124.124.124, 555.125.125.125,'''` do `txt = open("text.txt")` ?? – rmp5s Oct 29 '14 at 00:06