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

Alan Gauld alan.gauld at btinternet.com
Tue Aug 11 10:09:32 CEST 2015

On 11/08/15 01:23, Nym City via Tutor wrote:

> import socket
> import csv
> ListOfIPAddresses = []
> with open('top500ips.csv', 'rb') as f:
>      for line in f:
>          line = line.strip()
>          ListOfIPAddresses.append(line)
> f.close()

You don;t need the f.close(). The 'with' structiure
does that automatically.

> # print(ListOfIPAddresses)
> newFile = open('top500ips.csv', 'w')

The original file was opened in binary mode, you
are opening it here in text mode. Are you sure
that's correct? Do you undertand the significance
of binary v text modes?

Also 'w' mode effectively creates a new empty file
so you will need to recreate every line that was
in the input file. Its usually better to rename
the original file to something like top500ips.bak
and then create a new file with the original name.
If all goes well you can delete the .bak version,
if something goes wrong you can rename it back
to the original.

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

You save the result into the variable but do nothing with it.
The next time round the loop the result will be overwritten and the 
previous one lost. You are not writing anything to the file.

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

You are only writing to the file when you get the error.
But at that point ResolvedAddresses will contain the result from
the previous iteration of the loop so it may well be misleading.
You in effect only write the host to file for the entry
before lines that cause errors. I'm pretty sure thats not what
you want.

The other thing is that you are only writing the name. So your
file will only contain a short column of names. Again I don't
think that's what you wanted.

Can you send us an example of before and after?
ie about 5 lines of content from the file before you start
and what it should look like after you finish?

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list