tags:

views:

140

answers:

4

How to print the following code to a .txt file

y = '10.1.1.' # /24 network, 
for x in range(255):
    x += 1
    print y + str(x) # not happy that it's in string, but how to print it into a.txt

There's copy paste, but would rather try something more interesting.

+6  A: 
f = open('myfile.txt', 'w')
for x in range(255):
    ip = "10.1.1.%s\n" % str(x)
    f.write(ip)
f.close()
Harley
This won't give the result required: write() does not add newlines, so you end up with a single line of output.
mhawke
@mhawke: There's a newline character in ip, though.
Fred Larson
@Fred: yes, you're right. sorry about that. Anyway, there *is* a problem with the range(255) being zero-based.
mhawke
+3  A: 

scriptname.py >> output.txt

Mohamed
I think this is the more flexible solution.
Jeremy Cantrell
+1  A: 

What is the x += 1 for? It seems to be a workaround for range(255) being 0 based - which gives the sequence 0,1,2...254.

range(1,256) will better give you what you want.

An alternative to other answers:

NETWORK = '10.1.1'
f = open('outfile.txt', 'w')
try:
    for machine in range(1,256):
        print >> f, "%s.%s" % (NETWORK, machine)
finally:
    f.close()
mhawke
A: 

In Python 3, you can use the print function's keyword argument called file. "a" means "append."

f = open("network.txt", "a")
for i in range(1, 256):
    print("10.1.1." + str(i), file=f)
f.close()