在使用writerow写入csv之前删除括号

时间:2018-03-01 06:17:50

标签: python

def write_to_csv(file_name, header, numpy_data):
    with open(file_name, "w", newline='') as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        header = [header]
        for line in header:
            writer.writerow(line)

        for line in numpy_data:
            if line is None:
                writer.writerow(line)
            else:
                writer.writerow(line)

执行上面的代码

后,我的excel中的单元格就像这样
['Financial Analysis', 'Finance', 'Financial Modeling']

我想要的是

Financial Analysis, Finance, Financial Modeling

我尝试line.strip("[]")但是当我这样做时,excel中没有任何内容出现。

numpy_data的样本是:

[['Financial Analysis', 'Finance', 'Financial Modeling']]

谢谢

4 个答案:

答案 0 :(得分:1)

尝试:

def write_to_csv(file_name, header, numpy_data):
    with open(file_name, "w", newline='') as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        header = [header]
        for line in header:
            writer.writerow(line)

        for line in numpy_data:
            if line is None:
                writer.writerow(line)
            else:
                val = [", ".join(line[0])] + line[1:]  #--> ['Financial Analysis, Finance, Financial Modelling', '5000', 'Company A']
                writer.writerow(val)

答案 1 :(得分:0)

要从numpy数据中展开行,请使用*,如:

代码:

writer.writerow(*line)

整个清单:

def write_to_csv(file_name, header, numpy_data):
    with open(file_name, "w", newline='') as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        writer.writerow(header)
        for line in numpy_data:
            if line is None:
                writer.writerow(line)
            else:
                writer.writerow(*line)

答案 2 :(得分:0)

尝试在列表解析中使用join语句来标识列表的实例,并在将元素列表写入文件之前将它们转换为字符串。

line = [', '.join(i) if isinstance(i,list) else i for i in line]
writer.writerow(line)

答案 3 :(得分:0)

试试这个:

.join(',')

在您的文件中,导入以上文件,例如:

import csv, codecs, cStringIO
import threading


class UnicodeWriter:

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()
        self.lock = threading.RLock()

    def writerow(self, row):
        self.lock.acquire()
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)
        self.lock.release()

    def writerows(self, rows):
        self.lock.acquire()
        for row in rows:
            self.writerow(row)
        self.stream.flush()
        self.lock.release()
相关问题