【问题标题】:Python write to hdfs filePython写入hdfs文件
【发布时间】:2018-06-04 05:41:14
【问题描述】:

从本地 python 脚本在 remote HDFS 中创建/写入/更新文件的最佳方法是什么?

我可以列出文件和目录,但写作似乎是个问题。

我搜索了 hdfssnakebite,但没有一个提供干净的方法来做到这一点。

【问题讨论】:

    标签: python hadoop hdfs file-handling


    【解决方案1】:

    试试 HDFS 库.. 它真的很棒 您可以使用 write()。 https://hdfscli.readthedocs.io/en/latest/api.html#hdfs.client.Client.write

    例子:

    创建连接:

    from hdfs import InsecureClient
    client = InsecureClient('http://host:port', user='ann')
    
    from json import dump, dumps
    records = [
      {'name': 'foo', 'weight': 1},
      {'name': 'bar', 'weight': 2},
    ]
    
    # As a context manager:
    with client.write('data/records.jsonl', encoding='utf-8') as writer:
      dump(records, writer)
    
    # Or, passing in a generator directly:
    client.write('data/records.jsonl', data=dumps(records), encoding='utf-8')
    

    对于 CSV,您可以这样做

    import pandas as pd
    df=pd.read.csv("file.csv")
    with client_hdfs.write('path/output.csv', encoding = 'utf-8') as writer:
      df.to_csv(writer)
    

    【讨论】:

    • 为什么要用json库?是什么原因 ?如果我没有 json 但 CSV 怎么办?
    • 我已将其添加到答案中
    【解决方案2】:

    其他答案有什么问题

    他们使用 WebHDFS默认不启用,并且不安全没有 Kerberos 或 Apache Knox。

    这就是您链接到的 hdfs 库的 upload function 所使用的。

    使用 Python 写入 HDFS 的原生(更安全)方式

    您可以使用pyspark

    示例 - How to write pyspark dataframe to HDFS and then how to read it back into dataframe?


    snakebite已经提到了,但是it doesn't write files


    pyarrow has a FileSystem.open() function 也应该能够写入 HDFS,尽管我没有尝试过。

    【讨论】:

    • 这是真的..但如果他们在没有火花的情况下写入 hdfs,他们就不是其他很好的选择了。
    【解决方案3】:

    不使用为HDFS构建的复杂库,您也可以简单地使用python中的请求包为HDFS:

    import requests
    from json import dumps
    params = (
    ('op', 'CREATE')
    )
    data = dumps(file)  # some file or object - also tested for pickle library
    response = requests.put('http://host:port/path', params=params, data=data)
    

    如果响应为 200,那么您的连接正常!这种技术让您可以使用 Hadoop 的 RESTful API 提供的所有实用程序:ls、md、get、post 等。

    您还可以通过以下方式将 CURL 命令转换为 python:

    1. 获取 HDFS 的命令:https://hadoop.apache.org/docs/r1.0.4/webhdfs.html
    2. 转换成python:https://curl.trillworks.com/

    希望这会有所帮助!

    【讨论】:

    • 可能想用最新版本更新 Hadoop 链接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多