【问题标题】:How to append column onto csv on the fly如何即时将列附加到csv中
【发布时间】:2014-04-03 19:08:17
【问题描述】:

我正在尝试读取 CSV 的第一列,使用此列运行 Web 服务,从中获取输出并将其附加到我的 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

【问题讨论】:

    标签: python parsing csv append itertools


    【解决方案1】:

    你的row不是一个列表,而是一个字符串:

    row = row.split(sep, 1)[0]
    

    然后在subprocess 命令中使用该字符串。

    您需要再次列出它;而不是append,使用:

    row = [row, outrank1.rstrip()]
    

    其中outrank1 始终是一个字符串,无需调用str()

    请注意,如果您同时尝试读取和写入csvout 文件句柄,则必须非常小心您的读写位置。例如,您不能只写入文件句柄并希望替换现有数据。最好使用单独的新文件进行写入,并通过将一个移到另一个上来替换旧文件位置。

    【讨论】:

    • 非常感谢您的回复,我已经编辑了上面的代码以显示我当前正在运行的内容以及您的更改。尽管代码现在将运行,但它不会在我的输出中附加一列(实际上对输出文件没有任何影响)。有什么建议?谢谢你:)
    • 抱歉,我在那里复制了错误的文字!我现在已经更新了;它现在正在运行,但最终由于 IndexError 而失败。它还以不正确的格式打印我的输出,如下所示:i.imgur.com/borLltB.png。非常感谢您的帮助!:)
    • i.imgur.com/4uwgxPk.png 更好地说明了问题发生的原因 - 似乎是输出中的额外回车和引号。
    • 如果没有详细说明您的输入源产生了什么,这很难诊断。
    • 我的输入源是一个 csv,有四列。我在这里粘贴了一个摘录:pastebin.com/3HRGAP7Z。我只想运行我的 web 服务并逐行添加一个带有输出的列,但作为 Python 的新手,我发现它真的很难。非常感谢您的帮助:)
    猜你喜欢
    • 2015-03-06
    • 2014-05-13
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2017-06-30
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多