Skip to content
Bronze 8 min read · I/O 2 practice problems ↓

Reading and writing data

Every Spark job starts by reading data and ends by writing it. This lesson shows the one pattern behind every read and write, the options that matter for CSV, JSON and Parquet, why you should give Spark the schema, and which save mode can wipe a table by accident.

Step 1 · PySpark functions · Bronze · Read and select, lesson 1 of 5

In plain words first

Reading is like a librarian who checks the catalogue card at once but fetches the pages only when you start reading. Writing happens straight away, and you must say what to do if a book with that name is already on the shelf: replace it, add to it, or stop.

In Spark, the save mode is that "book already there" decision.

The shape of every read and write

Every source and sink in Spark goes through the same two builders. Reading is lazy: load only reads file footers or a sample to learn the schemaschema: The list of a DataFrame's columns and their types, such as order_id: long and city: string. Learn more →; the data is read when an action runs. Writing is an action: save starts a job immediately.

PySparkSpark SQL · Read and write
orders = (spark.read
    .format("csv")
    .option("header", True)
    .schema("order_id INT, customer STRING, amount DOUBLE, order_date DATE")
    .load("s3://raw/orders/"))

(orders.write
    .mode("overwrite")
    .partitionBy("order_date")
    .format("parquet")
    .save("s3://clean/orders/"))
CREATE TABLE clean_orders
USING parquet
PARTITIONED BY (order_date)
AS SELECT * FROM csv.`s3://raw/orders/`;

Shortcuts like spark.read.csv(path, header=True), spark.read.parquet(path) and df.write.parquet(path) are the same builders with the format filled in. saveAsTable("db.orders") writes and registers the table in the catalog, so others can query it by name.

The formats and their options

FormatOptions you will actually useNotes
CSVheader, sep, quote, escape, multiLine, nullValue, dateFormat, modeEverything is a string unless you give a schema. Slowest to read; no column pruningcolumn pruning: Reading only the columns a query uses, which columnar files like Parquet make possible. Learn more →.
JSONmultiLine (one document per file instead of one per line), mode, dateFormatDefault is JSON Lines: one object per line. Nested objects become structsstruct: A column that holds a small record with named fields, like an address with a city and a pin code. Learn more →.
ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more →mergeSchemaColumnar, compressed, typed. The schema is stored in the file, so no inference cost.
ORCsimilar to ParquetColumnar; common in Hive-era stacks.
Delta / IcebergversionAsOf, timestampAsOfParquet files plus a transaction logtransaction log: The ordered list of commits that defines which files make up a Delta table at each version. Learn more →. See the Lakehouse track.
JDBCurl, dbtable or query, partitionColumn, lowerBound, upperBound, numPartitionsWithout the partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → options, the whole table is read by one tasktask: The work for one partition in one stage, run on one CPU core. Learn more →.

Inferring vs passing a schema

inferSchema=True on CSV makes Spark read the data an extra time just to guess types, and the guess depends on the data it sees: a column of zip codes becomes an integer and loses its leading zeros, and a column empty in today's file becomes a string. Passing the schema is faster and gives the same result every day.

PySpark · Two ways to write a schema
from pyspark.sql.types import (
    StructType, StructField, IntegerType, StringType, DoubleType
)

# A DDL string: short and readable
schema = "order_id INT, customer STRING, amount DOUBLE"

# The same schema as objects, useful when you build it in code
schema = StructType([
    StructField("order_id", IntegerType(), nullable=False),
    StructField("customer", StringType()),
    StructField("amount", DoubleType()),
])
orders = spark.read.schema(schema).option("header", True).csv("s3://raw/orders/")

Bad records

CSV and JSON readers have three mode settings for rows that do not fit the schema:

modeWhat happens to a bad rowUse it when
PERMISSIVE (default)Bad fields become nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →. Add columnNameOfCorruptRecord to keep the raw line in a column.You want to load everything and quarantine bad rows afterwards
DROPMALFORMEDThe row is silently droppedRarely: you lose data without knowing how much
FAILFASTThe job fails on the first bad rowThe file must be perfect, for example a contract with a partner
Tip: in PERMISSIVE mode, count the rows where the corrupt-record column is not null and alert when it is above zero. Silent nulls are the most common cause of "the numbers look wrong" incidents.

Save modes

modeIf data already exists
errorifexists (default)Fail
appendAdd the new files next to the old ones. Running the job twice duplicates the data.
overwriteReplace the data. With partitionBy, it replaces every partition unless dynamic overwrite is on.
ignoreDo nothing, silently

partitionBy and overwriting one partition

partitionBy("order_date") writes one folder per value, such as order_date=2025-03-01/. Readers that filter on order_date skip the other folders entirely (partition pruning). Pick a low-cardinalitycardinality: How many distinct values a column has. User ids are high cardinality; country codes are low. Learn more → column that queries filter on; partitioning by a user id creates millions of folders of tiny files.

Step 1 · the table

The table at path holds 365 date folders. Today's job recomputes only 2025-03-01 because late data arrived; the recomputed rows are in the DataFrameDataFrame: A table of rows and named columns that Spark processes in parallel. It never changes: every operation returns a new one. Learn more → fixed_day.

Step 2 · static overwrite

With the default spark.sql.sources.partitionOverwriteMode=static, mode("overwrite") deletes all 365 folders and writes one. A year of data is gone.

The command

# deletes every other day
fixed_day.write.mode("overwrite").partitionBy("order_date").parquet(path)

Step 3 · dynamic overwrite

With dynamic, Spark replaces only the partitions present in the DataFrame being written. The other 364 folders are untouched.

The command

spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
fixed_day.write.mode("overwrite").partitionBy("order_date").parquet(path)
INSERT OVERWRITE TABLE orders PARTITION (order_date)
SELECT * FROM fixed_day;

Step 4 · with Delta

Delta Lake makes the intent explicit with replaceWhere, and checks that every row written matches the condition.

The command

fixed_day.write.format("delta").mode("overwrite") \
    .option("replaceWhere", "order_date = '2025-03-01'").save(path)

How many files a write produces

A write produces at least one file per task, and with partitionBy one per task per value. 200 tasks writing 30 dates can produce 6,000 files. repartition("order_date") before the write gives one file per date; .option("maxRecordsPerFile", n) caps the size of each file. More in The small file problem.

Try it yourself

Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.

Goal: Read a CSV with a fixed schema, set aside the rows that do not fit it, and write the good rows partitioned by date.

Production patternPySpark · Read with an explicit schema, quarantine bad records, write partitioned
import glob, os

os.makedirs("lab/io/raw", exist_ok=True)
with open("lab/io/raw/orders.csv", "w") as f:
    f.write("order_id,order_date,amount\n"
            "1,2025-03-01,120.5\n2,2025-03-01,oops\n3,2025-03-02,80\n")

schema = "order_id INT, order_date DATE, amount DOUBLE, _corrupt_record STRING"
orders = (spark.read
          .option("header", "true")
          .option("mode", "PERMISSIVE")
          .option("columnNameOfCorruptRecord", "_corrupt_record")
          .schema(schema)
          .csv("lab/io/raw")
          .cache())       # Spark refuses queries on only the corrupt column otherwise

good = orders.where("_corrupt_record IS NULL").drop("_corrupt_record")
bad = orders.where("_corrupt_record IS NOT NULL").select("_corrupt_record")
good.write.mode("overwrite").partitionBy("order_date").parquet("lab/io/orders")
bad.write.mode("overwrite").text("lab/io/quarantine")
orders.unpersist()

print("loaded:", spark.read.parquet("lab/io/orders").count(), "rows")
print("quarantined:", [r.value for r in spark.read.text("lab/io/quarantine").collect()])

print("files written under lab/io/orders:")
for f in sorted(glob.glob("lab/io/orders/**/*.parquet", recursive=True)):
    print(" ", f.removeprefix("lab/io/orders/"))
spark.read.parquet("lab/io/orders").orderBy("order_id").show()

Output from a real run

loaded: 2 rows
quarantined: ['2,2025-03-01,oops']
files written under lab/io/orders:
  order_date=2025-03-01/part-00000-5c53cda9-99b6-49b2-8e5e-06149bfe70c4.c000.snappy.parquet
  order_date=2025-03-02/part-00000-5c53cda9-99b6-49b2-8e5e-06149bfe70c4.c000.snappy.parquet
+--------+------+----------+
|order_id|amount|order_date|
+--------+------+----------+
|       1| 120.5|2025-03-01|
|       3|  80.0|2025-03-02|
+--------+------+----------+

What to notice:

  • 2 rows loaded, 1 quarantined: oops is not a number, so that whole line went to lab/io/quarantine exactly as it arrived.
  • Each date became a folder, order_date=2025-03-01 and order_date=2025-03-02, with the rows of that day inside.
  • Reading the folder back gives order_date as a normal column again: Spark takes it from the folder names.

Goal: Rewrite one day of a partitioned table without touching the other days.

Production patternPySpark · Re-run one day safely: dynamic partition overwrite
base = spark.createDataFrame(
    [("2025-03-01", 10), ("2025-03-02", 20), ("2025-03-03", 30)], ["day", "amount"])
base.write.mode("overwrite").partitionBy("day").parquet("lab/io/daily")

# re-run one day
backfill = spark.createDataFrame([("2025-03-02", 99)], ["day", "amount"])


def contents():
    rows = spark.read.parquet("lab/io/daily").collect()
    return sorted((str(r.day), r.amount) for r in rows)


spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
backfill.write.mode("overwrite").partitionBy("day").parquet("lab/io/daily")
print("dynamic:", contents())

# the default
spark.conf.set("spark.sql.sources.partitionOverwriteMode", "static")
backfill.write.mode("overwrite").partitionBy("day").parquet("lab/io/daily")
print("static: ", contents())
print("day is read back as:", spark.read.parquet("lab/io/daily").schema["day"].dataType)

Output from a real run

dynamic: [('2025-03-01', 10), ('2025-03-02', 99), ('2025-03-03', 30)]
static:  [('2025-03-02', 99)]
day is read back as: DateType()

What to notice:

  • dynamic: only 2025-03-02 changed (20 → 99); the other two days are still there.
  • static (the default): the same write deleted the whole table and left only the one new day.
  • day comes back as a DateType: Spark guesses column types from folder names.

Common mistakes

  • inferSchema in production — An extra pass over the data, and types that change when the data changes. Pass a schema.
  • mode("overwrite") with partitionBy and the default settings — Wipes every partition, not just the ones you wrote. Turn on dynamic overwrite or use Delta replaceWhere.
  • append in a job that can be retried — A retry writes the same rows again. Make the write idempotentidempotent: Safe to run again: running a step twice gives the same result as running it once. Learn more →: overwrite the partition, or MERGE.
  • Reading a large JDBC table without partition options — One task, one connection, and the job crawls. Set partitionColumn, bounds and numPartitions.

Key takeaways

  • Reading is lazy; writing starts a job.
  • Pass a schema for CSV and JSON instead of inferring it.
  • PERMISSIVE mode plus a corrupt-record column lets you load and then quarantine bad rows.
  • overwrite with partitionBy replaces everything unless dynamic overwrite is on.
  • Partition by a low-cardinality column that queries filter on.

Interview prep

THE QUESTION

"A daily job writes orders partitioned by date with mode('overwrite'). After a backfill of one day, the table only has that day. What happened?"

Static partition overwrite: by default, overwrite replaces the whole table, not only the partitions in the DataFrame. Set spark.sql.sources.partitionOverwriteMode=dynamic (or INSERT OVERWRITE ... PARTITION), or use Delta replaceWhere. Restore from a backup or, on Delta, with time travel / RESTORE. Mention making the job idempotent so reruns are safe.

Avoid: "overwrite deletes the table, so use append". Append would duplicate the day on a re-run; the fix is dynamic partition overwrite or a transactional replace.

Follow-ups · answer out loud, then open

Follow-up"Why pass a schema when reading CSV or JSON instead of inferSchema=True?"
Inference costs an extra pass over the data (a job before your job), can guess differently from one file to the next, and turns a column into a string when one bad value appears. An explicit schema is faster, stable across runs and documents the contract. Combine it with a mode such as PERMISSIVE plus columnNameOfCorruptRecord to catch bad rows.
Scenario"Some CSV files contain malformed rows. You must load the good rows and keep the bad ones for review."
Read with an explicit schema that includes a _corrupt_record string column, mode="PERMISSIVE" and columnNameOfCorruptRecord="_corrupt_record". Cache or write the result, then split: rows where it is null are good, the rest go to a quarantine table. Alternatively, badRecordsPath on Databricks writes them out for you.
Trap"mode('ignore') skips rows that fail to write."
No. Save modes are about the target as a whole: ignore silently does nothing if the target already exists. errorifexists (the default) fails, append adds, overwrite replaces.

Check yourself

3 questions

Which save mode duplicates data when a job is re-run?

Show the answer

append. append adds new files every time the job runs.

What does PERMISSIVE mode do with a row that does not fit the schema?

Show the answer

Sets the bad fields to null and keeps the row. It keeps the row with nulls, and can store the raw line in a corrupt-record column.

Why is inferSchema=True slow on CSV?

Show the answer

It reads the data an extra time to guess the types. Inference is a separate pass over the data before the real read.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Read and select · lesson 2 of 5 · 6 min read
select
Choose, rename and compute columns, and why select beats a chain of withColumn calls.

Related lessons

Primary sources: Data sources · CSV options · DataFrameWriter