简体   繁体   English

将数组保存在 csv 文件的单元格中

[英]Save an array in a cell in csv file

I want to write an array of numbers like [1,2,3,4] into a cell of csv file.我想将 [1,2,3,4] 之类的数字数组写入 csv 文件的单元格中。

My csv file should look like我的 csv 文件应该看起来像

 Title        array 

'file1' ,  '[1,2,3,4]'

'file2'  , '[3,4,5,6]'

'file3'  , '[6,8,2,9]'

I want to do this since i want to save this csv file in mysql database.我想这样做,因为我想将此 csv 文件保存在 mysql 数据库中。 So that i can retreive the data from the database later.这样我以后可以从数据库中检索数据。

Can anyone explain How to write this in python.谁能解释如何在 python 中写这个。 Thanks.谢谢。

So, for your testdata you can do it in this way所以,对于你的测试数据,你可以这样做

import csv
with open('example.csv', 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=',',escapechar=' ', quoting=csv.QUOTE_NONE)
    csvwriter.writerow(['file1' , '[1,2,3,4]'])
    csvwriter.writerow(['file2' , '[3,4,5,6]'])
    csvwriter.writerow(['file3' , '[6,8,2,9]'])

With this code I could create an csv-file, which you described.使用此代码,我可以创建一个您描述的 csv 文件。

import pandas as pd
import csv
sample=[[1,2,3,4],[3,4,5,6],[6,8,2,9]]
fileName=['file1','file2','file3']
df=pd.Series(sample)
df = df.to_frame()
df.rename(columns = {0:'Array'}, inplace = True)
df['Title']=fileName
cols = ['Title','Array']
df = df[cols]
df.to_csv('file1.csv',index=False)

Not quite sure I fully understand the question.不太确定我完全理解这个问题。 The CSV file will read comma separated values as individual cells by default, so likely your output will be like: 'file1', '[1, 2, 3, 4]' which will result in 5 columns, unless you change the delimited or the way you parse it.默认情况下,CSV 文件会将逗号分隔值读取为单个单元格,因此您的 output 可能类似于:'file1', '[1, 2, 3, 4]' 这将导致 5 列,除非您更改分隔或你解析它的方式。

But to get the output like you suggested the simple program like the following will do:但是要得到 output 像你建议的简单程序,如下所示:

f = open('out.csv', 'w+')
f.write("Title, array\n")
f.write("{0}, {1}".format(file_name, array_def))
f.close()

where for example例如在哪里

file_name = 'file1'
array_def = [1,2,3,4]

Hope that helps.希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM