Reputation: 5552
I use a .writer()
method in a loop, as shown in the Python documentation.
I want to write the results of the variable u
, row by row (or better line by line).
Actually it works perfectly in the interpreter but the module writerow()
doesn't seem to work. Why?
from urlparse import urlparse
import csv
import re
ifile =open(ipath,'r')
ofile = open(opath, 'wb')
writer = csv.writer(ofile, dialect='excel')
url =[urlparse(u).netloc for u in file (ipath, "r+b")]
sitesource = set([re.sub("www.", "", e) for e in url])
liste = [re.split(",'", e) for e in liste]
ofile
for row in file (ifile) :
for u in sitesource:
print ("Creation de:", u)
writer.writerow(u)
ofile.close()
I'm using Python 2.7.
Upvotes: 2
Views: 21589
Reputation: 45542
Guessing at you really mean, I would rewrite your code as follows:
from urlparse import urlparse
import csv
import re
ifile =open(ipath,'r')
ofile = open(opath, 'wb')
writer = csv.writer(ofile, dialect='excel')
url =[urlparse(u).netloc for u in ifile]
sitesource = set([re.sub("www.", "", e) for e in url])
for u in sitesource:
print ("Creation de:", u)
writer.writerow([u])
ofile.close()
ifile.close()
I deleted liste
as it's not used. I got rid of for row in file (ifile):
as you already iterated over its contents when you created url
.
I changed
url =[urlparse(u).netloc for u in file (ipath, "r+b")]
to
url =[urlparse(u).netloc for u in ifile]
because you already had the file open. I assumed you did not want binary mode if you are reading strings.
I changed writerow(u)
to write a sequence: writerow([u])
. This puts a single u
per line, which means your csv file will not acutally have any commas in it. If you wanted all of your results in a single row, replace the final loop with this statment writer.writerow(sitesource)
.
Upvotes: 5
Reputation: 123393
writerow()
expects a sequence argument, so I think you need to use writer.writerow([u])
since each u
is a single string -- otherwise you're passing it a sequence of characters doing it the way you currently have it.
Upvotes: 2
Reputation: 7924
Not entirely sure, but csv.writer.writerow wants a sequence (i always use it with lists) with the fields for the whole row, and you are iterating over a set of what which returns what in u?
Upvotes: 0
Reputation: 3130
Are you trying to write the string "u"? or the contents of the variable ? If it's the latter option, then remove the parentheses.
Upvotes: 0