【发布时间】:2016-09-04 04:11:06
【问题描述】:
我正在尝试使用 python as 从 hdfds 读取文件
from hdfs.client import Client
import json,requests
if __name__ == '__main__':
cl = Client("http://hostName:port")
print cl.list("/myDir/")
with cl.read("/myDir/myFile.json") as f:
print f
print json.load(f)
但我明白了
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
在json.load(f)
我也试过了
with cl.read("/myDir/myFile.json", encoding ="utf-8") as f:
但现在我明白了
UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: invalid start byte
然后我尝试了
with cl.read("/myDir/myFile.json",encoding ="utf-8", errors='ignore') as f:
但我明白了
TypeError: read() got an unexpected keyword argument 'errors'
有什么方法可以将文件作为简单字符串读取?该文件看起来像
{"key1":"val1","key2":"val2","key3":"val3"...}
我正在使用 python 2.7
更新
感谢@Yaron 的有用建议。经过一番摆弄,我想出了这个
r=requests.get('http://hostName:port/webhdfs/v1/myDir/myFile.json?op=OPEN', stream=True)
r.raw.decode_content = True
print r
print str(r.raw.read())
但是,由于某种原因,它不会读取整个文件。它只是停在中间,我不知道为什么。有什么想法吗?
另外,我仍然无法将其转换为 JSON。我试过了
r=requests.get('http://hostName:port/webhdfs/v1/myDir/myFile.json?op=OPEN', stream=True)
r.raw.decode_content = True
print r
x=r.raw.read()
# print x["key1"] fails citing that string indices must be integers
print x
x=json.loads(str(x))
我明白了
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb0 in position 0: invalid start byte
回到第 1 格!
终于明白了
我要做的就是
r=requests.get('http://hostName:port/webhdfs/v1/myDir/myFile.json?op=OPEN', stream=True)
r.raw.decode_content = True
print r
x=r.raw.read().decode("utf-8",errors="ignore")
print json.loads(x)["key1"]
这给了我
<Response [200]>
value2
:)
【问题讨论】:
-
不要运行“json.load(f)” - 你能尝试执行“json.loads(f)”吗?
-
TypeError: expected string or buffer -
print f给出<requests.packages.urllib3.response.HTTPResponse object at 0x0000000006768K0G1>所以它显然是某种对象。有没有办法使用requests.get()阅读此内容 -
stackoverflow.com/a/16924225/5088142 - 说明您可以使用 object..raw.read(10) 读取 requests.packages.urllib3.response.HTTPResponse 对象 - 例如f.raw.read(10)
-
请在下面添加您的解决方案作为答案,而不是将其添加到问题中
标签: python json hadoop hdfs python-requests