【发布时间】:2018-06-04 05:41:14
【问题描述】:
从本地 python 脚本在 remote HDFS 中创建/写入/更新文件的最佳方法是什么?
我可以列出文件和目录,但写作似乎是个问题。
【问题讨论】:
标签: python hadoop hdfs file-handling
从本地 python 脚本在 remote HDFS 中创建/写入/更新文件的最佳方法是什么?
我可以列出文件和目录,但写作似乎是个问题。
【问题讨论】:
标签: python hadoop hdfs file-handling
试试 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)
【讨论】:
他们使用 WebHDFS,默认不启用,并且不安全没有 Kerberos 或 Apache Knox。
这就是您链接到的 hdfs 库的 upload function 所使用的。
您可以使用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构建的复杂库,您也可以简单地使用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:
希望这会有所帮助!
【讨论】: