简体   繁体   English

从文件中读取数据作为列表

[英]reading data from file as list

i have file on s3 that contains 我在s3上包含的文件

[{
        'address': 'Bramalea, L6T 0E2'
        'type': 'home'
      }, {
        'address': 'A, 46 Peel Drive, ASDF23'
        'type': 'office'
      }
}]

i just wanted to read addresses that has type office , can any body suggest me how i can iterate this data ? 我只想阅读具有office 类型的 地址 ,有人可以建议我如何迭代此数据吗? because its just a string so far i am able to read this data 因为到目前为止它只是一个字符串,我已经能够读取此数据

conn = S3Connection(AWS_KEY, AWS_SECRET)
bucket = conn.get_bucket(BUCKET_NAME)
for key in bucket.list(DIR_Name):
    data =  key.get_contents_as_string()
    print data

i also tried reading data using json module 我也尝试使用json模块读取数据

data =  key.get_contents_as_string()
print json.loads(data)

its raising 它的提高

    print json.loads(data)
  File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 2 column 5 (char 8)

It is not necessary to use an other module. 无需使用其他模块。 As this is a list of dictionaries, it is easy to keep only elements with 'type' that are 'office' : 由于这是词典的列表,因此很容易仅保留具有'office' 'type'元素:

my_list = [{
    'address': 'aa, 46 Peel Centre Drive, A342',
    'type': 'home',
  }, {
    'address': 'a, 46 Peel Centre Drive, AS32',
    'type': 'office',
  }, {
    'address': 'b, 46 Peel Centre Drive, SD22',
    'type': 'home',
  }, {
    'address': 'c, 46 Peel Centre Drive, SD22',
    'type': 'home',
  }, {
    'address': 'd, 46 Peel Centre Drive, SSD222',
    'type': 'office',
  }]
addresses = [elem['address'] for elem in my_list if elem['type'] == 'office']
print addresses

I was incorrect in my comment to your post. 我对您的帖子的评论不正确。 Do not use the json module to parse this file because this is not valid json. 不要使用json模块来解析此文件,因为这不是有效的json。 Valid json only uses double quotes around its strings - not single quotes. 有效json仅在其字符串周围使用双引号-而不是单引号。 Instead, this looks like basic python literal structures (read: basic python data types). 相反,这看起来像基本的python文字结构(阅读:基本的python数据类型)。 There is a method to safely do this with potentially untrusted sources. 有一种方法可以对可能不受信任的来源安全地执行此操作。 ast.literal_eval should be able to help you here. ast.literal_eval应该可以在这里为您提供帮助。

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

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