[Tutor] Writing back to same CSV in the next column

Nym City nymcity at yahoo.com
Sun Aug 23 15:16:45 CEST 2015

Here is my final script. It is doing what I wanted it to. I wanted to just share it as a final product and thank you all for your feedback on the various previous revisions. 

import socket

ListOfIPAddresses = []

with open('top500ips.csv', 'r') as f:
    for line in f:
        line = line.strip()

newFile = open('top500ips.csv', 'w')

for address in ListOfIPAddresses:
        ResolvedAddresses = socket.gethostbyaddr(address)[0]
        newFile.write(ResolvedAddresses + "\n")
        # print(ResolvedAddresses)
    except socket.herror as e:
        newFile.write("No resolution available for %s" % (address) + "\n")

----------------------------If you have any suggestions, please do share. 

Thank you. 

     On Monday, August 17, 2015 4:35 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:

 On 17/08/15 02:51, Nym City via Tutor wrote:
 > the output of the gethostbyaddr module includes three item
> (hostname, aliaslist, ipaddrlist). However, in my output
> I just what the hostname field. So I created a list but
> I am not able to pull out just the [0] item from this
 > and instead I get the following error:
 > TypeError: 'int' object is not subscriptable.

> for line in in_file:
>      try:
>          name = socket.gethostbyaddr(line.strip())
>          ListOfIPAddresses.append(name)
>          out_file.write(str(ListOfIPAddresses))[0]

Look at that last line and break it down.
Where is the index operation?

It's right at the end so it applies to the output
of the write() operation. You need it against
the list, before you convert to string and before
you write to file.

> Also, could you please give some explanation of '\t'.

Its the tab character. it inserts a tab, just like hitting
the tab key on the keyboard.
Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:


More information about the Tutor mailing list