Sunday, March 27, 2011

Outputting to a text file

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.

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

    Jeremy Cantrell : I think this is the more flexible solution.
  • 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()
    
  • 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()
    

0 comments:

Post a Comment