Python - 如何将数组写入文本文件?

时间:2015-02-22 00:42:14

标签: python arrays file text

我每分钟都会通过网页抓取生成两个数组。下面有两个。如何将它们放在文本文件中?我希望每个数组占用一行,我希望它们保留括号和逗号。我没有找到有关此问题的其他主题的帮助。

[('76,433', '15.025'), ('99,714', '15.023'), ('44,236', '15.010'), ('718,725', '15.000'), ('30', '15.000'), ('30', '15.000'), ('15', '15.000'), ('15', '15.000'), ('15', '15.000'), ('15', '15.000'), ('60', '15.000'), ('30', '15.000'), ('15', '15.000'), ('30', '15.000'), ('30', '15.000'), ('60', '15.000'), ('30', '15.000'), ('30', '15.000'), ('15', '15.000'), ('30', '15.000')]

[('18,622', '15.027'), ('334', '15.029'), ('3,240', '15.032'), ('11,354', '15.032'), ('13,651', '15.033'), ('96', '15.041'), ('1,997', '15.051'), ('1,760', '15.051'), ('500', '15.052'), ('16,000', '15.053'), ('272', '15.091'), ('3,834', '15.097'), ('8', '15.125'), ('634', '15.141'), ('794', '15.143'), ('528', '15.149'), ('220', '15.150'), ('94', '15.159'), ('91', '15.164')]

3 个答案:

答案 0 :(得分:2)

考虑到您希望Rbx.Lua脚本使用该文件,您可能最好使用JSON。

repr可能会生成一行,但您需要在Lua中自己解析它。也许并不太难,但如果您想要交换其他数据类型,则需要修改Lua代码。您可能还会发现repr并不总能为您提供有用的东西。

使用JSON很简单:

的Python:

import json

l = [('76,433', '15.025'), ('99,714', '15.023'), ('44,236', '15.010'), ('718,725', '15.000'), ('30', '15.000'), ('30', '15.000'), ('15', '15.000'), ('15', '15.000'), ('15', '15.000'), ('15', '15.000'), ('60', '15.000'), ('30', '15.000'), ('15', '15.000'), ('30', '15.000'), ('30', '15.000'), ('60', '15.000'), ('30', '15.000'), ('30', '15.000'), ('15', '15.000'), ('30', '15.000')]

with open('l.json', 'w') as outfile:
    json.dump(l, outfile)

$ cat l.json
[["76,433", "15.025"], ["99,714", "15.023"], ["44,236", "15.010"], ["718,725", "15.000"], ["30", "15.000"], ["30", "15.000"], ["15", "15.000"], ["15", "15.000"], ["15", "15.000"], ["15", "15.000"], ["60", "15.000"], ["30", "15.000"], ["15", "15.000"], ["30", "15.000"], ["30", "15.000"], ["60", "15.000"], ["30", "15.000"], ["30", "15.000"], ["15", "15.000"], ["30", "15.000"]]

请参阅http://wiki.roblox.com/index.php?title=JSON了解Rbx.Lua结尾;您可以使用DecodeJSON()转换为Lua表。

答案 1 :(得分:1)

尝试使用这样的repr函数,它将保持数组结构的完整性:

v = [('76,433', '15.025'), ('99,714', '15.023'), ('44,236', '15.010'), ('718,725', '15.000'), ('30', '15.000'), ('30', '15.000'), ('15', '15.000'), ('15', '15.000'), ('15', '15.000'), ('15', '15.000'), ('60', '15.000'), ('30', '15.000'), ('15', '15.000'), ('30', '15.000'), ('30', '15.000'), ('60', '15.000'), ('30', '15.000'), ('30', '15.000'), ('15', '15.000'), ('30', '15.000')]
f.write(repr(v))

详细了解here

答案 2 :(得分:0)

你可以将它们转换为str,然后写入文件:     演示:

f = open('your_file', 'w')
a = ['1', '2', '3']
f.write(str(a)+"\n")
回读时,您可以使用ast.literal_eval

import ast
f = open("your_file")
for x in f:
    x = ast.literal_eval(x.strip())
    # now do your stuff