0
我想讀取我的CSV的第一列,使用此列運行Web服務,從此輸出並將其附加到我的CSV。我想在逐行的基礎上做到這一點。如何在列上將列追加到csv上
以下是我想出迄今:
loadData = lambda f: np.genfromtxt(open(f,'r'), delimiter='\n')
with open('FinalCSV.csv','rb') as tsvin, open('FinalCSV.csv', 'a+b') as csvout:
tsvin = list(np.array(p.read_table('train.tsv'))[:,0])
writer = csv.writer(csvout)
count = 0
for row in csvout:
sep = '|'
row = row.split(sep, 1)[0]
cmd = subprocess.Popen("python GetJustAlexaRanking.py " + row ,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
(output, err) = cmd.communicate()
exit_code = cmd.wait()
outlist = output.split('\r\n')
try:
outrank1 = outlist[1][outlist[1].index(':')+1:]
except ValueError:
outrank1 = "?"
row.append(str(outrank1).rstrip()) #writing,error here
print [str(outlist[0]).rstrip(), str(outrank1).rstrip()]
count+=1
然而,這是給我的是
Traceback (most recent call last):
File "File.py", line 28, in <module>
row.append(str(outrank1).rstrip()) #writing,error here
AttributeError: 'str' object has no attribute 'append'
我怎麼能做到什麼,我希望做的錯誤?
編輯:
loadData = lambda f: np.genfromtxt(open(f,'r'), delimiter='\n')
with open('FinalCSV.csv','rb') as tsvread, open('FinalCSVFin.csv', 'wb') as csvout:
tsvin = list(np.array(p.read_table('train.tsv'))[:,0])
writer = csv.writer(csvout)
count = 0
for row in tsvread:
sep = '|'
row = row.split(sep, 1)[0]
cmd = subprocess.Popen("python GetJustAlexaRanking.py " + row ,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
(output, err) = cmd.communicate()
exit_code = cmd.wait()
outlist = output.split('\r\n')
try:
outrank1 = outlist[1][outlist[1].index(':')+1:]
except ValueError:
outrank1 = "?"
row = [row, outrank1.rstrip()]
writer.writerow(row)
print [str(outlist[0]).rstrip(), str(outrank1).rstrip()]
count+=1
非常感謝您的回覆,我已經編輯了上面的代碼以顯示我目前正在運行的更改。雖然代碼現在可以運行,但它不會將列添加到我的輸出中(實際上對輸出文件沒有影響)。有什麼建議麼?謝謝:) –
@SimonKiely:你不會*寫*行到一個文件.. –
道歉,我在那裏複製了錯誤的文本!我現在更新了它;它現在正在運行,但最終由於IndexError而失敗。它也以不正確的格式打印我的輸出,如下所示:http://i.imgur.com/borLltB.png。非常感謝您的幫助!:) –