使用python从每一行读取选定的文本

时间:2015-03-21 09:40:05

标签: python file

我有一个包含

字符串的文件
[{"resourceId": "sid-14E51598-BEE7-45E0-9974-A38B07CE6892"}]
[{"resourceId": "sid-A5B57DEB-C024-4D89-AD99-86FC340A6742"}]
[{"resourceId": "sid-3775C783-4491-44B9-904C-1763C080E9C6"}]    
[{"resourceId": "sid-8F636B07-3010-4D27-9E9B-08DB1D25AC96"}]

我希望使用python从每一行获得sid-8F636B07-3010-4D27-9E9B-08DB1D25AC96。我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

如果您的文件名为test.txt:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

with open('test.txt') as fh:
    for line in fh:
        data = json.loads(line)
        print data[0]['resourceId']

答案 1 :(得分:0)

根据双引号分割每一行,然后打印第三个索引。

with open('file') as f:
    for line in f:
        print(line.split('"')[3])

答案 2 :(得分:0)

您可以使用ast.literal_eval解析内部列表:

from ast import literal_eval

with open("in.txt") as f:
    for line in f:
        print(literal_eval(line)[0]["resourceId"])

sid-14E51598-BEE7-45E0-9974-A38B07CE6892
sid-A5B57DEB-C024-4D89-AD99-86FC340A6742
sid-3775C783-4491-44B9-904C-1763C080E9C6
sid-8F636B07-3010-4D27-9E9B-08DB1D25AC96

如果所有项目都用双引号括起来,请使用json.loads

from json import loads

with open("in.txt") as f:
    for line in f:
        print(loads(line)[0]["resourceId"])

sid-14E51598-BEE7-45E0-9974-A38B07CE6892
sid-A5B57DEB-C024-4D89-AD99-86FC340A6742
sid-3775C783-4491-44B9-904C-1763C080E9C6
sid-8F636B07-3010-4D27-9E9B-08DB1D25AC96

如果您不确定密钥名称,只需访问值:

from json import loads
with open("in.txt") as f:
    for line in f:
        print(list(loads(line)[0].values())[0])