Python .csv 编写器
我在循环中使用 .writer()
方法,如 Python 文档中所示。 我想逐行(或者更好地逐行)写入变量 u
的结果。
实际上它在解释器中工作得很好,但模块 writerow()
似乎不起作用。为什么?
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()
我正在使用Python 2.7。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
猜测你的意思是,我会重写你的代码如下:
我删除了
liste
因为它没有被使用。我摆脱了for row in file (ifile):
因为您在创建url
时已经迭代了其内容。我改为
因为
你已经打开了文件。我假设如果您正在读取字符串,您不想要二进制模式。
我更改了 writerow(u) 来编写序列:writerow([u])。这会在每行放置一个
u
,这意味着您的 csv 文件中实际上不会包含任何逗号。如果您希望所有结果都在一行中,请使用此语句writer.writerow(sitesource)
替换最终循环。Guessing at you really mean, I would rewrite your code as follows:
I deleted
liste
as it's not used. I got rid offor row in file (ifile):
as you already iterated over its contents when you createdurl
.I changed
to
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 singleu
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 statmentwriter.writerow(sitesource)
.writerow()
需要一个序列参数,所以我认为你需要使用writer.writerow([u])
因为每个u
都是一个单独的字符串——否则你将向它传递一个字符序列,按照你当前的方式进行操作。writerow()
expects a sequence argument, so I think you need to usewriter.writerow([u])
since eachu
is a single string -- otherwise you're passing it a sequence of characters doing it the way you currently have it.你想写字符串“u”吗?或者变量的内容?如果是后一个选项,则删除括号。
Are you trying to write the string "u"? or the contents of the variable ? If it's the latter option, then remove the parentheses.
不完全确定,但是 csv.writer.writerow 想要一个带有整行字段的序列(我总是将它与列表一起使用),并且您正在迭代一组返回 u 中的内容的内容?
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?