-1

Morning I wonder if anyone can point me in the right direction Im new to Python and just starting to learn how it works ?

As a test Im reading internal IP's from a text file running a loop with nslookup which runs fine. But im not sure how to export the results into a new text file called results. Im pretty sure i need to use the Python library to output the results from os.system("nslookup " + line) to results.txt but am getting lost.....any help appreciated

import os 

fh = open('pa2.txt','r+')
fh2 = open('results.txt','w+')

while True:
    line = fh.readline
    os.system("nslookup " + line)   
    fh2.writelines(results.txt)

        if not line:
            break

f.close()
Carlos Gonzalez
  • 858
  • 13
  • 23
FiveTen
  • 1
  • 3

1 Answers1

1

i think you are better off separating the reading and writing of the data into two separate functions. Something like this:

import os

def read():
    with open('pa2.txt','r+') as fh:
        lines = fh.read()
        for line in lines:
            os.system('nslookup' + str(line))
            print(line)
            write(line)

def write(res):
    with open('results.txt','w+') as fh2:
        fh2.write(res)


if __name__ == "__main__":
    read()

You may need to edit to suit your particular desired result

Nick
  • 3,454
  • 6
  • 33
  • 56
  • Thanks Nick that sounds sensible to split and define the read from the write. Ive tried to amend and run the above but i keep getting indentation Tab errors. Im only getting used to Python so trying to adjust by lining up but no luck. Also what does the "If" statement at the end do ? – FiveTen Nov 06 '18 at 12:03
  • @FiveTen yes in python the indentation matters. See - https://docs.python.org/2.0/ref/indentation.html . "The if statement tells the program that the code inside this if statement should only be executed if the program is executed as a standalone program. It will not be executed if the program is imported as a module." – Nick Nov 06 '18 at 13:00