Python HDFS : Cannot read file

标签 python json hadoop hdfs python-requests

我正在尝试使用 python 从 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

:)

最佳答案

1) 参见pypi.python.org/pypi/hdfs - 我会一步一步地遵循他们的示例(这看起来与你所做的非常相似) - 并确保问题不在 python 代码中。 2) 下一步是确认 /myDir/myFile.json 确实存在于 HDFS 中,并保存有效的 json 文件。

stackoverflow.com/a/16924225/5088142 - 说明您可以使用 object.raw.read(10) 读取 requests.packages.urllib3.response.HTTPResponse 对象 - 例如f.raw.read(10)

关于Python HDFS : Cannot read file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37117227/

相关文章:

java - Hadoop Reducer在JAVA中两次迭代

python - 如何在 Django 中自定义 slug 字段?

python - 无法让 flask 运行

python - key 错误 : Timestamp when converting date in column to date

javascript - 我怎样才能迭代这个json?

Hadoop NameNode 启动失败,错误 : FSNamesystem initialization failed. java.io.FileNotFoundException

scala - 从 Spark 中以 Map(String,List(String)) 形式列出/检索 HDFS 分区

python - 设置默认国家

json - Swift 4 可解码,直到解码时才知道 key

c# - 从 jquery Ajax 调用 WCF 服务