[英]reading data from file as list
我在s3上包含的文件
[{
'address': 'Bramalea, L6T 0E2'
'type': 'home'
}, {
'address': 'A, 46 Peel Drive, ASDF23'
'type': 'office'
}
}]
我只想阅读具有office 类型的 地址 ,有人可以建议我如何迭代此数据吗? 因为到目前为止它只是一个字符串,我已经能够读取此数据
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
我也尝试使用json模块读取数据
data = key.get_contents_as_string()
print json.loads(data)
它的提高
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)
无需使用其他模块。 由于这是词典的列表,因此很容易仅保留具有'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
我对您的帖子的评论不正确。 不要使用json
模块来解析此文件,因为这不是有效的json。 有效json仅在其字符串周围使用双引号-而不是单引号。 相反,这看起来像基本的python文字结构(阅读:基本的python数据类型)。 有一种方法可以对可能不受信任的来源安全地执行此操作。 ast.literal_eval
应该可以在这里为您提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.