[Tutor] Writing back to same CSV in the next column
nymcity at yahoo.com
Wed Aug 12 02:58:47 CEST 2015
Please find the two requested files attached. The 'before' file is what I am reading into my program. The 'after' file is what I would like to have my output to look like. Ideally, I want it to be the same file but if its easier to create a new file for the output - that is ok too.
I do not have the understanding of binary vs text modes. But I have found this online, can't say I understand it though: http://fileinfo.com/help/binary_vs_text_files Thank you.
On Tuesday, August 11, 2015 4:10 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
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()
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:
> ResolvedAddresses = socket.gethostbyaddr(address)
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
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?
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