2

.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。

4

4 回答 4

5

猜你的意思是,我会重写你的代码如下:

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()

因为没用所以删liste了。我摆脱了for row in file (ifile):你在创建时已经迭代了它的内容url

我变了

url =[urlparse(u).netloc for u in file (ipath, "r+b")]

url =[urlparse(u).netloc for u in ifile]

因为你已经打开了文件。如果您正在阅读字符串,我假设您不想要二进制模式。

我改写writerow(u)了一个序列:writerow([u]). 这将每行放置一个u,这意味着您的 csv 文件中实际上不会有任何逗号。如果您希望将所有结果放在一行中,请将最后一个循环替换为该语句writer.writerow(sitesource)

于 2011-04-18T14:45:08.593 回答
2

writerow()需要一个序列参数,所以我认为您需要使用writer.writerow([u]),因为每个u都是一个字符串 - 否则您将按照您当前拥有的方式传递一个字符序列。

于 2011-04-18T13:22:22.693 回答
0

你想写字符串“u”吗?还是变量的内容?如果是后一种选择,则删除括号。

于 2011-04-18T11:11:58.897 回答
0

不完全确定,但 csv.writer.writerow 想要一个序列(我总是将它与列表一起使用),其中包含整行的字段,并且您正在迭代一组返回 u 中的内容的内容?

于 2011-04-18T13:15:41.177 回答