python如何将列表列表写入文件 [英] python how to write list of lists to file

查看:925
本文介绍了python如何将列表列表写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串列表列表写入文件. 我的大清单是有名无实的:

I am trying to write a list of lists of strings to a file. My big list is of the forme:

 1.0 '0:25.0' '1:50.0' '2:131.0' '3:202.0'
 1.0 '0:2.0'  '1:36.0' '2:131.0' '3:188.0'
-1.0 '0:56.0' '1:53.0' '2:55.0'  '3:58.0'
-1.0 '0:50.0' '1:51.0' '2:48.0'  '3:55.0'  
 and so on ... 

第一列的类型为int,其余的类型为str.

the first column is of type int and the remaining are of type str.

我尝试了以下代码:

f = open('dataset', 'w')
for i in range(len(mylist[0]):
     f.write(str(item) for item in mylist[i])
f.close()

但是出现以下错误:

TypeError: expected a character buffer object

上述代码(f.write(...))的第3行中发生了错误

the error occured in line 3 of the above code (f.write(...))

我尝试过:

 with open("train_data.csv", 'w') as f:
     writer = csv.writer(f)
     writer.writerows(listdata)

但是,令人惊讶的是,对于以-1.0开头的行,我只得到1st 31个元素(每行(列表)包含362个元素).我不知道为什么会这样.

But, surprisingly, for lines starting with -1.0 I only get the 1st 31 elements ( each line (list) contains 362 elements). I have no idea why this is happening.

推荐答案

我会这样.

from __future__ import with_statement

mylist = [[1.0,'0:25.0','1:50.0'],[-1.0,'0:56.0','1:53.0']] # as example

with open('output.txt', 'w') as f:
    for _list in mylist:
        for _string in _list:
            #f.seek(0)
            f.write(str(_string) + '\n')

结果,我在output.txt中得到了它:

As a result, I get this in output.txt:

1.0
0:25.0
1:50.0
-1.0
0:56.0
1:53.0

这篇关于python如何将列表列表写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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