using text file to get ip address from hostname

Chris Angelico rosuav at gmail.com
Wed Sep 12 10:35:30 EDT 2012


On Thu, Sep 13, 2012 at 12:24 AM,  <dkatorza at gmail.com> wrote:
> i'm new to Python and i searched the web and could not find an answer for my issue.
>
> i need to get an ip address from list of hostnames which are in a textfile.

This is sounding like homework, so I'll just give you a basic pointer.

You have there something that successfully resolves one hostname to an
IP address. Now you want to expand that to reading an entire file of
them and resolving them all. Presumably you need to produce a list of
IP addresses; check the question as to whether you need to create a
file, or output to the screen, or something else.

What you want, here, is to open a file and iterate over it. The most
convenient way would be to have one hostname per line and iterate over
the lines of the file. Check out these pages in the Python docs
(you're using Python 2 so I'm going with Python 2.7.3 documentation):

Opening a file:
http://docs.python.org/library/functions.html#open
Ensuring that it'll be closed when you're done:
http://docs.python.org/reference/compound_stmts.html#the-with-statement
Looping over an iterable:
http://docs.python.org/tutorial/controlflow.html#for-statements

See where that takes you; in fact, all of
http://docs.python.org/tutorial/ is worth reading, if you haven't
already.

Have fun, enjoy Python!

ChrisA



More information about the Python-list mailing list