[英]Python .csv writer
I use a .writer()
method in a loop, as shown in the Python documentation. 我在循环中使用
.writer()
方法,如Python文档中所示。 I want to write the results of the variable u
, row by row (or better line by line). 我想逐行(或更好地逐行)编写变量
u
的结果。
Actually it works perfectly in the interpreter but the module writerow()
doesn't seem to work. 实际上,它在解释器中可以正常运行,但是模块
writerow()
似乎不起作用。 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. 我正在使用Python 2.7。
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. 我删除了
liste
因为它没有被使用。 I got rid of for row in file (ifile):
as you already iterated over its contents when you created url
. 我摆脱了
for row in file (ifile):
中for row in file (ifile):
因为创建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])
. 我更改了
writerow(u)
来编写一个序列: writerow([u])
。 This puts a single u
per line, which means your csv file will not acutally have any commas in it. 这会在每行中放一个
u
,这意味着您的csv文件中不会包含任何逗号。 If you wanted all of your results in a single row, replace the final loop with this statment writer.writerow(sitesource)
. 如果您希望所有结果都放在一行中,请使用此声明
writer.writerow(sitesource)
替换最终循环。
writerow()
需要一个序列参数,所以我认为您需要使用writer.writerow([u])
因为每个u
是一个字符串-否则,您将按照目前的方式将一系列字符传递给它。
Are you trying to write the string "u"? 您是否要写字符串“ u”? or the contents of the variable ?
还是变量的内容? If it's the latter option, then remove the parentheses.
如果是后者,请删除括号。
不确定,但是csv.writer.writerow想要一个包含整个行字段的序列(我总是将其与列表一起使用),并且您正在遍历一组返回u中的内容的内容?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.