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

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


Hello,
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()
        ListOfIPAddresses.append(line)

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

for address in ListOfIPAddresses:
    try:
        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
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


 
  


More information about the Tutor mailing list