python hdfs:无法读取文件

zed5wv10  于 2021-05-29  发布在  Hadoop
关注(0)|答案(3)|浏览(518)

我正在尝试从hdfds读取一个文件,使用python作为

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"...}

我使用的是python2.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

:)

cpjpxq1n

cpjpxq1n1#

您是否尝试过以下方法之一:
毒蛇咬伤或
hdfs3型
这些应该允许以非常简单的方式将文件作为python中的简单内容进行读取。另外,这些是纯python hdfs客户机,而不是web/httphdfs Package 器。
以蛇咬伤为例:

from snakebite.client import AutoConfigClient
c = AutoConfigClient()
next(c.text([“/user/r/foobar.txt"]))
`awesome foobar content`

编辑:说到json示例:

> jq . test.json
{
   "bar": "test",
   "foo": 1
}
> hdfs dfs -put test.json
> snakebite cat test.json | jq .
{
   "bar": "test",
   "foo": 1
}
> python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from snakebite.client import AutoConfigClient
>>> c = AutoConfigClient()
>>> import simplejson as json
>>> next(c.text(["test.json"]))
'{"foo": 1, "bar": "test"}\n'
>>> json.loads(next(c.text(["test.json"])))
{'foo': 1, 'bar': 'test'}
juud5qan

juud5qan2#

with cl.read('/myDir/myFile.json', encoding='utf-8') as reader:
       from json import load
        model = load(reader)
dsekswqp

dsekswqp3#

1) 请参阅pypi.python.org/pypi/hdfs—我将一步一步地遵循他们的示例(这似乎与您所做的非常相似)—并确保问题不在python代码中。2) 下一步是确认 /myDir/myFile.json 实际上存在于hdfs中,并保存一个有效的json文件。
stackoverflow.com/a/16924225/5088142-说明您可以阅读 requests.packages.urllib3.response.HTTPResponse 对象使用 object.raw.read(10) -例如。 f.raw.read(10)

相关问题