将数据写入csv文件Python

时间:2014-11-24 00:33:01

标签: python python-2.7 csv export-to-csv

我的数据如下所示

['[\'Patient, A\', \'G\', \'P\', \'RNA\']']

无论括号,引号和反斜杠如何,我都想将数据分开,','并写入CSV文件,如下所示

Patient,A,G,P,RNA

提及分隔符=','没有帮助。然后输出文件看起来像

['Patient, A','G','P','RNA']

全部在一个单元格中。我想将它们分成多列。我怎么能这样做?

编辑 - 提及quotechar='|'将它们分成不同的单元格但现在看起来像

|['Patient, A','G','P','RNA']|

编辑 -

out_file_handle = csv.writer(out_file, quotechar='|', lineterminator='\n', delimiter = ",")
data = ''.join(mydict.get(word.lower(), word) for word in re.split('(\W+)', transposed))
data = [data,]
out_file_handle.writerow(data)

转置:

['Patient, A','G','P','RNA']

数据:

['[\'Patient, A\', \'G\', \'P\', \'RNA\']']

它有多行,上面是整个数据中的一行。

4 个答案:

答案 0 :(得分:1)

首先需要将此数据读入Python数组,方法是将字符串作为内存中的CSV文件处理:

from StringIO import StringIO
import csv
data = ['[\'Patient, A\', \'G\', \'P\', \'RNA\']']
clean_data = list(csv.reader( StringIO(data[0]) ))

然而,输出仍然是单个字符串,因为它甚至不是格式良好的CSV!在这种情况下,最好的办法就是过滤掉所有垃圾字符?

import re
clean_data = re.sub("[\[\]']","",data[0])

现在数据[0]为'Patient, A, G, P, RNA',这是一个干净的CSV,您可以直接写入文件。

答案 1 :(得分:1)

Python有一个CSV编写器。从

开始
import csv

然后尝试这样的事情

with open('new.csv', 'wb') as write_file:
    file_writer = csv.writer(write_file)
    for i in range(data):
        file_writer.writerow([x for x in data[i]])

编辑:

在编写数据之前,您可能需要先对数据进行一些争论,因为它看起来像是一个字符串而不是实际上是一个列表。尝试使用split()函数

list = data.split()

答案 2 :(得分:1)

如果你要做的是以['[\'Patient, A\', \'G\', \'P\', \'RNA\']']的形式写数据,你有一个这些字符串的数组,要提交,那么它实际上是一个问题分两部分。

第一个,是如何将数据分成正确的格式,然后第二个是将其写入文件。

如果这是您的数据的形式,对于每一行,那么这样的事情应该起作用(使其成为正确的格式):

data = ['[\'Patient, A\', \'G\', \'P\', \'RNA\']', ...]
newData = [entry.replace("\'", "")[1:-1].split(",") for entry in data]

将以下列形式为您提供数据:

[["Patient", "A", "G", "P", "RNA"], ...]

然后您可以按照其他答案中的建议将其写入文件;

with open('new.csv', 'wb') as write_file:
  file_writer = csv.writer(write_file)
  for dataEntry in range(newData ):
    file_writer.writerow(dataEntry)

如果您实际上并不关心在这一轮中使用数据,只想清理它,那么您只需执行data.replace("\'", "")[1:-1]然后将这些字符串写入文件。

[1:-1]位只是用于删除前导和尾随方括号。

答案 3 :(得分:0)

"""
                             SAVING DATA INTO CSV FORMAT
    * This format is used for many purposes, mainly for deep learning.
    * This type of file can be used to view data in MS Excel or any similar 
      Application
"""
# == Imports ===================================================================

import csv
import sys

# == Initialisation Function ===================================================

def initialise_csvlog(filename, fields):
    """
    Initilisation this function before using the Inserction function

    * This Function checks the data before adding new one in order to maintain
      perfect mechanisum of insertion
    * It check the file if not exists then it creates a new one
    * if it exists then it proceeds with getting fields

    Parameters
    ----------
    filename : String
        Filename along with directory which need to be created
    Fields : List
        Colomns That need to be initialised

    """
    try :
        with open(filename,'r') as csvfile:
            csvreader = csv.reader(csvfile)
            fields = csvreader.next()
            print("Data Already Exists")
            sys.exit("Please Create a new empty file")
            # print fields  
    except :
        with open(filename,'w') as csvfile:

            csvwriter = csv.writer(csvfile)
            csvwriter.writerow(fields)

# == Data Insertion Function ===================================================

def write_data_csv(filename, row_data):
    """
    This Function save the Row Data into the CSV Created
    * This adds the row data that is Double Listed

    Parameters
    ----------
    filename : String
        Filename along with directory which need to be created
    row_data : List
        Double Listed consisting of row data and column elements in a list  
    """
    with open(filename,'a') as csvfile:

        csvwriter = csv.writer(csvfile)
        csvwriter.writerows(row_data)

if __name__ == '__main__':
    """
    This function is used to test the Feature Run it independently

    NOTE: DATA IN row_data MUST BE IN THE FOLLOWING DOUBLE LISTED AS SHOWN
    """
    filename = "TestCSV.csv"
    fields = ["sno","Name","Work","Department"]
    #Init
    initialise_csvlog(filename,fields)
    #Add Data
    row_data = [["1","Jhon","Coder","Pythonic"]]
    write_data_csv(filename,row_data)

# == END =======================================================================

阅读模块,您可以开始使用CSV并在Excel或任何类似的应用程序中查看数据(在libreoffice中计算)

  

注意:请记住将要列出的数据列表放在__main__函数(row_data)

中。