简体   繁体   English

如何在 python 中保存 csv 字符串文件

[英]How to save a csv string file in python

I am new with python.我是 python 的新手。

I have a loop with lime function which generate an output at each iteration:我有一个带有石灰 function 的循环,它在每次迭代时生成一个 output:

file = []
res = output.as_list() at i=0 It contains [('ft-1822 > 0.45', -0.1625), ('ft-1818 > 0.18', -0.109)]
file.append(res)
res = output.as_list() at i=1 It contains [('ft-1822 > 0.45', -0.1658), ('ft-1818 > 0.18', -0.1118)]
file.append(res)
res = output.as_list() at i=2 It contains [('ft-1822 > 0.45', -0.15975), ('ft-1818 > 0.18', -0.111309)]
file.append(res)

The final file contains:最终文件包含:

[[('ft-1822 > 0.45', -0.1625), ('ft-1818 > 0.18', -0.109)], [('ft-1822 > 0.45', -0.1658), ('ft-1818 > 0.18', -0.1118)], [('ft-1822 > 0.45', -0.15975), ('ft-1818 > 0.18', -0.111309)]]

I want to save it in an csv file with 2 columns and 3 rows:我想将其保存在具有 2 列和 3 行的 csv 文件中:

[('ft-1822 > 0.45', -0.1625), ('ft-1818 > 0.18', -0.109)]
[('ft-1822 > 0.45', -0.1658), ('ft-1818 > 0.18', -0.1118)]
[('ft-1822 > 0.45', -0.15975), ('ft-1818 > 0.18', -0.111309)]

I tried this but I am getting all value in one row我试过了,但我在一行中获得了所有价值

with open('file.csv', 'w') as f:
    wr = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    wr.writerow(file)

Using Pandas, we can do this as follow:使用 Pandas,我们可以这样做:

import pandas as pd
df = pd.DataFrame(input_list)
df.to_csv(output_path, index = False)

There are probably much more elegant ways, but a simple way of doing this is like the following:可能有更优雅的方法,但一种简单的方法如下:

mytuples = [[('ft-1822 > 0.45', -0.1625), ('ft-1818 > 0.18', -0.109)], [('ft-1822 > 0.45', -0.1658), ('ft-1818 > 0.18', -0.1118)], [('ft-1822 > 0.45', -0.15975), ('ft-1818 > 0.18', -0.111309)]]
with open('test.csv','w') as f:
    for mytuple in mytuples:
        f.write(str(mytuple)+ '\n')

You loop over the list and convert your list element into a string adding a Newline and then writing that list element to the file.您遍历列表并将列表元素转换为添加换行符的字符串,然后将该列表元素写入文件。

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

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