簡體   English   中英

Python .csv編寫器

[英]Python .csv writer

我在循環中使用.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。

猜測您的意思是,我將按照以下方式重寫您的代碼:

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):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)替換最終循環。

writerow()需要一個序列參數,所以我認為您需要使用writer.writerow([u])因為每個u是一個字符串-否則,您將按照目前的方式將一系列字符傳遞給它。

您是否要寫字符串“ u”? 還是變量的內容? 如果是后者,請刪除括號。

不確定,但是csv.writer.writerow想要一個包含整個行字段的序列(我總是將其與列表一起使用),並且您正在遍歷一組返回u中的內容的內容?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM