text (DataFrameWriter)

将文本文件中的内容 DataFrame 保存在指定路径处。 文本文件编码为 UTF-8。

Syntax

text(path, compression=None, lineSep=None)

参数

参数 类型 说明
path str 任何 Hadoop 支持的文件系统中的路径。
compression str,可选 要使用的压缩编解码器。
lineSep str,可选 要使用的行分隔符。

退货

没有

备注

DataFrame必须只有一列字符串类型。 每行将成为输出文件中的新行。

示例

将 DataFrame 写入文本文件,并将其读回。

import tempfile
with tempfile.TemporaryDirectory(prefix="text") as d:
    df = spark.createDataFrame([("a",), ("b",), ("c",)], schema=["alphabets"])
    df.write.mode("overwrite").text(d)

    spark.read.schema(df.schema).format("text").load(d).sort("alphabets").show()
    # +---------+
    # |alphabets|
    # +---------+
    # |        a|
    # |        b|
    # |        c|
    # +---------+