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

Alan Gauld alan.gauld at btinternet.com
Sun Aug 23 16:33:13 CEST 2015


On 23/08/15 14:16, Nym City wrote:
> 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)
The initial assignment plus this for loop could all be
replaced by readlines():

ListOfIPAddresses = f.readlines()
>
> newFile = open('top500ips.csv', 'w')

You should use the 'with' style that you used above.
Otherwise you should definitely close the file after the loop below.
Do one or the other, but not both...

> for address in ListOfIPAddresses:
>     try:
>         ResolvedAddresses = socket.gethostbyaddr(address)[0]

Being picky this variable should probably be named ResolvedAddress
since its only one address being resolved at a time.

>         newFile.write(ResolvedAddresses + "\n")
>         # print(ResolvedAddresses)
>     except socket.herror as e:
>         newFile.write("No resolution available for %s" % (address) + "\n")

Otherwise it looks fine to me.

-- 
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



More information about the Tutor mailing list