CSV.writerow为何在每个字符之间加逗号?

1 投票
2 回答
4860 浏览
提问于 2025-04-17 20:20

我现在在我的Python脚本里调用另一个Python脚本,并试图把调用的结果保存到一个CSV文件里。目前这个过程是可以工作的,但输出的结果每个字符之间都有一个逗号,所以结果是错误的。

这是什么原因呢?

import csv
import GetAlexRanking #External Method exposed here
import subprocess
import pandas as p
import tai
import numpy as np

loadData = lambda f: np.genfromtxt(open(f,'r'), delimiter=' ')
with open('train.tsv','rb') as tsvin, open('PageRanks.csv', 'wb') as csvout:
    tsvin = list(np.array(p.read_table('train.tsv'))[:,0])
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = 0
        cmd = subprocess.Popen("python GetAlexRanking.py " + row ,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE,
                           shell=True)
        (output, err) = cmd.communicate()
        exit_code = cmd.wait()
        print exit_code #testing
        print output
        print err
        csvout.writerow(row + "\t" + output) #writing,error here
        count+=1

编辑:

当我在命令行中这样调用函数时,返回的一个示例行是 "python GetAlexRanking.py www.google.com" :

www.google.com
AlexaTrafficRank:1
GooglePageRank:9

我希望这个结果能以制表符分隔的格式保存成一个tsv文件(为了让格式更清晰,我加了空格,所有列之间只用一个制表符分隔 :))

URL \t AlexaRank \t GoogleRank
www.google.com \t 1 \t 9

2 个回答

1

看起来你想要输入和输出都是一个列表。所以,保持你的输入为一组字符串,然后在每一行进行拆分,变成列表。

你给的示例行显示了三行。这是否意味着它是一个很长的字符串,中间用分隔符分开的?如果是这样的话,就把输出拆分开,并插入制表符。

  outrow = row # row is already a list
  outrow.append(output.split('\t'))
  csvout.writerow(outrow)

再看看你的示例,似乎你想输出两行tsv,一行是“标题”,另一行是“排名”。所以(为了更容易阅读,增加了额外的行)

outlist = output.split('\t')
outname1 = outlist[1][0:outlist[1].index(':')-1]
outname2 = outlist[2][0:outlist[2].index(':')-1]
outrank1 = outlist[1][outlist[1].index(':')+1:]
outrank2 = outlist[2][outlist[2].index(':')+1:]
outrow1 = ['URL', outname1, outname2]
outrow2 = [outlist[0], outrank1, outrank2]

然后你就可以像你在示例输出中那样写出这两行输出。

4

你把一个字符串传给了csv.write,它把这个字符串当成了一个列表来处理,所以就把它按每个列表元素,也就是每个字符分开了。我自己也犯过这个错误好多次……

试试这个:

# add coustom code to split the row up into the values, hint user row.split()
csvout.writerow([row, output]) 

撰写回答