导入文件并将整数转换为int

时间:2016-09-30 10:10:44

标签: list python-2.7 python-import

我遇到了以下问题。 我导入一个看起来像[[58,59,60]]的文件。 打印它会给出[' [[58,59,60]]']。 现在我只想将58 59 60添加到新列表中。问题是:

output gives ['[[58, 59, 60]]']
output[0] gives '[[58, 59, 60]]'
output[0][2] gives '5'
output[0][3] gives '8'.

有没有办法以只加载完整整数的方式导入文件?

with open('file', 'r') as fobj:
     content = int(fobj.read())

1 个答案:

答案 0 :(得分:0)

从文件中读取时,可以使用json从字符串转换为实际列表。

例如:

import json

def get_output(filename):     # filename is name of text file
    with open(filename) as fn:
        output = json.loads(fn.read())
        return output

如果文件&#t; t.txt'包含:[[58, 59, 60]],然后get_output('t.txt')返回列表[[58, 59, 60]]

output = get_output('t.txt')
type(output)       # ===> list
output[0]          # ===> [58, 59, 60]
output[0][2]       # ===> 60
相关问题