csv writer在每个单词中添加分隔符。 [英] csv writer is adding delimiters in each words..

查看:1043
本文介绍了csv writer在每个单词中添加分隔符。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一些代码,它使用一个ids检查复制列表,并写一个id列表。没有什么奇怪只是我工作的一小部分..

I wrote some throw away code which takes a list of ids checks for duplicates and writes a list of ids. Nothing fancy just a small part of what I am working on..

我得到这个奇怪的输出。它看起来像我,分隔符是添加空间,它不应该。分隔符是在单词还是行之间?很困惑。

I get this weird output. It looks to me like the delimiter is adding spaces where it shouldn't. Is delimiter just between words or line ? Very confused.

r s 9 3 6 4 5 5 4
r s 9 3 1 1 1 7 1 
r s 7 8 9 0 2 0 2 5 
r s 7 6 5 2 3 3 1 
r s 7 2 1 0 4 8 
r s 6 9 8 3 2 6 7 
r s 6 4 6 5 6 5 7
r s 6 2 9 2 4 2 
r s 6 1 9 9 1 1 5 6

__author__ = 'prumac'
import csv

allsnps = []

def open_file():
    ifile  = open('mirnaduplicates.csv', "rb")
    print "open file"
    return csv.reader(ifile)

def write_file():
    with open('mirnaduplicatesremoved.csv', 'w') as fp:
        a = csv.writer(fp, delimiter=' ')
        a.writerows(allsnps)


def checksnp(name):
    if name in allsnps:
        pass
    else:
        allsnps.append(name)

def mymain():
    reader = open_file()
    for r in reader:
        checksnp(r[0])
    print len(allsnps)
    print allsnps
    write_file()

mymain()


推荐答案

.writerows()需要一个列表列表。

.writerows() expects a list of lists. Instead, you are handing it a list of strings, and these are treated as sequences of characters.

将每个字符串放在一个元组或列表中:

Put each string in a tuple or list:

a.writerows([val] for val in allsnps)

请注意,您可以更高效地执行此操作:

Note that you could do this all a little more efficiently:

with open('mirnaduplicates.csv', "rb") as ifile, \
     open('mirnaduplicatesremoved.csv', 'wb') as fp:
    reader = csv.reader(ifile)
    writer = csv.writer(fp, delimiter=' ')

    seen = set()
    seen_add = seen.add
    writer.writerows(row for row in reader if row[0] not in seen and not seen_add(row[0]))

这篇关于csv writer在每个单词中添加分隔符。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆