温馨提示×

spark读取本地文件的方法有哪些

小亿
104
2024-03-28 14:13:58
栏目: 大数据

在Spark中,可以使用以下几种方式来读取本地文件:

  1. 使用sc.textFile()方法读取文本文件:
from pyspark import SparkContext

sc = SparkContext("local", "FileReader")

file_path = "file:///path/to/file.txt"
lines = sc.textFile(file_path)
  1. 使用spark.read.csv()方法读取CSV文件:
from pyspark.sql import SparkSession

spark = SparkSession.builder.master("local").appName("FileReader").getOrCreate()

file_path = "file:///path/to/file.csv"
df = spark.read.csv(file_path, header=True, inferSchema=True)
  1. 使用spark.read.json()方法读取JSON文件:
from pyspark.sql import SparkSession

spark = SparkSession.builder.master("local").appName("FileReader").getOrCreate()

file_path = "file:///path/to/file.json"
df = spark.read.json(file_path)

这些是一些常见的方法,可以根据实际需求选择合适的方法来读取本地文件。

0