How to use spark.read.text() In Python
It is used to load text files into DataFrame whose schema starts with a string column. Each line in the text file is a new row in the resulting DataFrame. Using this method we can also read multiple files at a time.
Syntax: spark.read.text(paths)
Parameters: This method accepts the following parameter as mentioned above and described below.
- paths: It is a string, or list of strings, for input path(s).
Returns: DataFrame
Example : Read text file using spark.read.text().
Here we will import the module and create a spark session and then read the file with spark.read.text() then create columns and split the data from the txt file show into a dataframe.
Python3
from pyspark.sql import SparkSession spark = SparkSession.builder.appName( "DataFrame" ).getOrCreate() df = spark.read.text( "output.txt" ) df.selectExpr("split(value, ' ' ) as\ Text_Data_In_Rows_Using_Text").show( 4 , False ) |
Output:
Read Text file into PySpark Dataframe
In this article, we are going to see how to read text files in PySpark Dataframe.
There are three ways to read text files into PySpark DataFrame.
- Using spark.read.text()
- Using spark.read.csv()
- Using spark.read.format().load()
Using these we can read a single text file, multiple files, and all files from a directory into Spark DataFrame and Dataset.
Text file Used:
Contact Us