Reading and writing
Part of the free LogicWiz Data Engineering course, Module 11: PySpark DataFrames. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:10 on Tuesday. Tess opens the pricing dashboard and SwiftKart's most expensive order line costs $9.99. On Monday it was $89.00. Nothing failed overnight. The only change: you took one option out of the nightly read to make it faster.
You'll learn to
- Read CSV, JSON and Parquet with a schema you wrote
- Choose what Spark does with a line that does not fit
- Explain what a write does underneath, and why renames hurt
- Predict how many files a write makes, and rerun one day safely
Learn
A CSV carries no types
The nightly job starts with spark.read. The formats it reads differ in how much they tell Spark (Module 4):
- CSV is plain text. No types, no nesting: every value is a string until something decides otherwise.
- JSON has numbers, text, true/false, objects and lists, but no dates and no column order.
- Parquet stores the schema with the data, typed and compressed.
The order lines arrive as CSV. The option you removed was inferSchema=True, which asks Spark to guess the types. Without it, real Spark reads every CSV column as a string. So unit_price is text now.
Ask a text column for its highest price
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
# What real Spark gives you when you forget inferSchema: every column is a string
as_text = spark.read.csv(
"data/order_items.csv", header=True,
schema="order_id STRING, line_no STRING, product_id STRING, qty STRING, unit_price STRING",
)
print("max price as text: ", as_text.agg(F.max("unit_price").alias("m")).first()["m"])
typed = as_text.withColumn("unit_price", F.col("unit_price").cast("double"))
print("max price as number:", typed.agg(F.max("unit_price").alias("m")).first()["m"])
The same column, as text and then as a number. The browser engine detects numbers in a CSV even without inferSchema, so this card passes an all-string schema to show what Databricks would hand you.
The distinct prices, sorted as text and as numbers
| Sorted as text (highest first) | Sorted as numbers (highest first) |
|---|---|
| "9.99" | 89.0 |
| "89.00" | 80.1 |
| "80.10" | 65.0 |
| "8.99" | 59.99 |
| "8.75" | 54.0 |
Text is compared one character at a time, like words in a dictionary, so "9" beats "8" and "9.99" wins. No error, no warning: only a wrong answer.
Why not put the guess back?
The quick fix is to put inferSchema=True back. Nora says no, for two reasons.
The guess costs a full extra read. Spark's documentation is blunt: "It requires one extra pass over the data."
The guess depends on the data. The day a product id arrives as N/A, the column becomes a string and every join on it breaks. samplingRatio (default 1.0) guesses from a fraction of the rows, and may miss the one row that would widen a type.
Give the schema yourself
Production jobs do not guess. They hand Spark the schema: the column names and types, written down. Build it as a StructType, or write it as one line of text, a DDL string: "order_id INT, qty INT, unit_price DOUBLE".
One trap. Spark applies your schema by position and ignores the header names (enforceSchema is true by default). If a file arrives with its columns reordered, prices load into qty and nothing complains. enforceSchema=False makes Spark check the header.
Read the orders with a schema you wrote
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.types import StructType, StructField, IntegerType, StringType, TimestampType
spark = SparkSession.builder.getOrCreate()
schema = StructType([
StructField("order_id", IntegerType()),
StructField("customer_id", IntegerType()),
StructField("order_ts", TimestampType()),
StructField("status", StringType()),
StructField("currency", StringType()),
StructField("updated_at", TimestampType()),
])
orders = spark.read.csv("data/orders.csv", header=True, schema=schema)
orders.printSchema()
# The same schema as a DDL string: shorter, and easy to keep in a config file
ddl = "order_id INT, customer_id INT, order_ts TIMESTAMP, status STRING, currency STRING, updated_at TIMESTAMP"
same = spark.read.csv("data/orders.csv", header=True, schema=ddl)
print(same.schema.simpleString())
print("rows:", same.count())
The types now say int and timestamp, as they would on Databricks, because you chose them. The column order in the schema must match the file's.
Remember: a CSV has no types. Give the schema in the read, and a number is a number from line one.
When a line does not fit
What should Spark do with a line that does not fit the schema, such as a quantity of two? The mode option decides:
PERMISSIVE(the default): keep the row, and put null in the bad field.DROPMALFORMED: drop the whole row, silently.FAILFAST: stop the read with an error.
Permissive mode can also keep the evidence. Add a string column named _corrupt_record to your schema, and Spark stores the raw line there for every bad row.
Step through one small file, and watch line 3.
One bad file, three modes
A CSV file with four lines, one with a bad value and one with a missing field, is read in PERMISSIVE, DROPMALFORMED and FAILFAST mode, and the rows each mode returns are shown beside it.
The file. Four data lines, read with the schema
order_id INT, qty INT, unit_price DOUBLE, _corrupt_record STRING. Line 2 saystwowhere a number should be. Line 3 stops after two fields.PERMISSIVE, the default. All four rows stay. Row 2 gets a null
qtyand its raw line in_corrupt_record. Row 3 is short, so its price is null, but it is not corrupt.DROPMALFORMED. Row 2 is gone, and no message says so. Row 3 still comes back with its null price.
FAILFAST. The read stops at line 2 with
[MALFORMED_RECORD_IN_PARSING]. No rows come back.
Left: the file. Right: what each mode returns.
The same file on Databricks
Runs on Databricks:
# bad_lines.csv:
# order_id,qty,unit_price
# 1,2,9.99
# 2,two,5.00
# 3,1
# 4,1,1.50
path = "/Volumes/main/swiftkart/raw/bad_lines.csv"
ddl = "order_id INT, qty INT, unit_price DOUBLE, _corrupt_record STRING"
for mode in ["PERMISSIVE", "DROPMALFORMED"]:
rows = spark.read.csv(path, header=True, schema=ddl, mode=mode).collect()
print(mode, [tuple(r) for r in rows])
spark.read.csv(path, header=True, schema=ddl, mode="FAILFAST").collect()
PERMISSIVE [(1, 2, 9.99, None), (2, None, 5.0, '2,two,5.00'), (3, 1, None, None), (4, 1, 1.5, None)]
DROPMALFORMED [(1, 2, 9.99, None), (3, 1, None, None), (4, 1, 1.5, None)]
SparkException: ... Malformed records are detected in record parsing: ... Parse Mode: FAILFAST. To process malformed records as null result, try setting the option 'mode' as 'PERMISSIVE'.
Databricks only: the browser engine has no parse modes. Every mode keeps line 3 with a null price: count nulls after the read, not only corrupt records. In production, count _corrupt_record IS NOT NULL and quarantine those rows (Module 7); on Databricks, Auto Loader's _rescued_data column does the same job for schema drift.
Night two: what a rerun does
The read is fixed. Now the other half: df.write.mode(m).parquet(path). Pipelines land raw CSV and JSON, then write Parquet (or Delta) for everyone downstream.
On night two something is already at path. The save mode says what happens then:
errorifexists(the default): stop with an error.overwrite: replace everything at the path.append: add these rows next to what is there.ignore: do nothing if the path exists.
The mode is a decision about reruns (Module 6). Append is fast and dangerous: a retried job adds the same rows twice. Overwrite is safe to rerun, but it replaces the whole path.
Write Parquet twice, then read it back
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
orders = spark.read.csv(
"data/orders.csv", header=True,
schema="order_id INT, customer_id INT, order_ts TIMESTAMP, status STRING, currency STRING, updated_at TIMESTAMP",
)
orders.write.mode("overwrite").parquet("orders.parquet")
orders.write.mode("overwrite").parquet("orders.parquet") # a rerun: still one copy
back = spark.read.parquet("orders.parquet")
print("rows after two runs:", back.count())
print("types kept:", back.schema.simpleString())
try:
orders.write.parquet("orders.parquet") # the default mode
except Exception as e:
print("default mode refused:", type(e).__name__)
Two overwrites leave one copy, the types come back, and the default mode refuses an existing path. Write to a top-level name, or create the folder first with os.makedirs. The browser engine writes one file, not a folder, and does not support append.
What a write does underneath
On a cluster many tasks write at once, each holding one slice of the rows. So a write makes a folder: one part-... file per task, plus an empty _SUCCESS marker.
Tasks can fail and be retried, so Spark never writes straight into the final folder. Think of a kitchen pass: each cook plates on the side, and the whole table goes out together. Each task writes under a hidden _temporary folder, and at the end the driver moves every file into place. These rules are the commit protocol.
The move is a rename. On HDFS, and on ADLS Gen2 with its real folders (a hierarchical namespace), that is one metadata operation: no bytes move. On S3 and Google Cloud Storage it is a copy plus a delete per file.
One write, from task files to _SUCCESS
Two write tasks put their part files under a hidden _temporary folder, one attempt per task is allowed to commit, then the driver renames every file into the orders folder, writes a _SUCCESS marker and deletes _temporary.
Tasks write to the side. Each task writes its file, such as
part-00007-<uuid>-c000.snappy.parquet, underorders/_temporary/0/_temporary/<attempt>/. Task 7 has a duplicate attempt, which Spark may start for a slow task.Task commit. Each finished attempt asks the driver for permission. Only the attempt the driver authorises may commit, so the duplicate cannot. The winner renames its attempt folder to
_temporary/0/<task>/.Job commit. The driver renames every committed file into
orders/. On S3 or Google Cloud Storage this is the slow part: one copy and one delete per file. A reader listingorders/now can see half the files.Done. The driver writes an empty
_SUCCESSmarker and deletes_temporary. Downstream jobs wait for the marker. Delta avoids the renames: its commit is one log entry (Module 13).
Watch the two folders: files reach orders/ only at job commit.
Three tasks, three days, nine files
Analysts filter by day, so the job writes one sub-folder per day: df.write.partitionBy('order_date').parquet(path) makes order_date=2025-06-01/, order_date=2025-06-02/ and so on. Pick a column that queries filter on, with a modest number of values: a day, never a customer id.
Each task writes one file into every folder its rows touch. Below, three tasks hold rows from three days, so nine files appear.
The fix is one line before the write. repartition('order_date') sends each day to one task: one file per folder. A huge day then becomes one huge task, so the write option maxRecordsPerFile splits its file.
Every task writes into every folder it touches
Three write tasks on the left each send an arrow to all three date folders on the right, one file per task per folder, nine files in all.
Count the arrows: each one is a file. After repartition("order_date") each folder gets its rows from exactly one task, so three files.
One month of orders: 600 million rows, 30 days, 200 tasks
| Write | Files | Rows per file |
|---|---|---|
| partitionBy("orderdate") straight after a 200-partition shuffle | 200 x 30 = 6,000 | about 100,000 |
| repartition("orderdate") first | 30 | about 20,000,000 |
| repartition("orderdate") + maxRecordsPerFile=5000000 | 30 x 4 = 120 | 5,000,000 |
600 million rows over 30 days is 20 million a day; over 200 tasks that is 100,000 rows per task per day. Aim for files of roughly 100 MB to 1 GB, and let Delta or Iceberg compaction (OPTIMIZE, Module 13) fix the rest.
Rerun one day, keep the month
One morning the 2 June file turns out to be wrong, and you rerun that day: you write the corrected rows with mode('overwrite') to the partitioned path.
What happens to the other days? One setting decides: spark.sql.sources.partitionOverwriteMode. Its default is static. Step through both values.
The same overwrite, static and dynamic
A table folder with three day folders is overwritten with corrected rows for one day: in static mode the other two days are deleted, in dynamic mode only the one day is replaced.
Before the rerun.
orders/holds three days and 1,500 rows. The 2 June folder came from a bad file, and you have 470 corrected rows for it.Overwrite in static mode, the default. Spark deletes every partition first, then writes the one day it was given. 470 rows are left out of 1,500, with no error.
Overwrite in dynamic mode. Spark writes to a staging folder,
.spark-staging-<jobId>, then replaces only the partitions present in the new data. 1 June and 3 June keep their rows: 500 + 470 + 520 = 1,490.
Compare the right-hand box in steps 2 and 3. The row counts are made up for the example.
The fixed write, and a one-day rerun (Databricks)
Runs on Databricks:
from pyspark.sql import functions as F
path = "/Volumes/main/swiftkart/curated/orders"
(orders
.withColumn("order_date", F.to_date("order_ts"))
.repartition("order_date") # one task per day: one file per folder
.write.mode("overwrite")
.option("maxRecordsPerFile", 5_000_000) # split a very big day
.partitionBy("order_date")
.parquet(path))
print([f.name for f in dbutils.fs.ls(path) if f.name.startswith("order_date=")][:3])
# Rerun one day: replace only the partitions present in the new data
spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
(fixed_june_2
.withColumn("order_date", F.to_date("order_ts"))
.write.mode("overwrite")
.partitionBy("order_date")
.parquet(path))
['order_date=2025-06-01/', 'order_date=2025-06-02/', 'order_date=2025-06-03/']
Databricks only: the browser engine supports neither partitionBy nor maxRecordsPerFile on a write. Spark leaves order_date out of the files and rebuilds the column from the folder names when you read the top folder with spark.read.parquet(path).
What the day folders buy the reader
Files sit in one folder per day; setting a date filter shows which folders a query opens and which it skips.
Set the filter to one day and count the folders a reader can skip.
The trap: picking a save mode without asking "what if this runs twice, or dies halfway?" Append is not idempotent: a retried job doubles that day's rows. A static overwrite with one day of data deletes every other day. And a plain Parquet write on S3 that dies during job commit leaves some files renamed and some not: readers see a partial day and no error.
Numbers to remember
| Setting or name | Default | What to know |
|---|---|---|
| inferSchema (CSV) | off | One extra pass over the data when on. JSON read without a schema always makes that pass. |
| enforceSchema | true | Schema by position; header names ignored. |
| mode (read) | PERMISSIVE | FAILFAST stops with [MALFORMEDRECORDINPARSING], SQLSTATE 22023. |
| columnNameOfCorruptRecord | corruptrecord | Session default: spark.sql.columnNameOfCorruptRecord. For CSV the column must be in your schema; JSON inference adds it on its own. Spark parses only the columns a query needs, so which records are corrupt can change with the query. A query that reads only this column from a raw file is refused: cache the parsed DataFrame first. |
| Parquet compression | snappy | Hence part-00007-<uuid-c000.snappy.parquet. |
| FileOutputCommitter algorithm | v1 | On S3 and GCS, Spark's cloud page calls v1 "very, very slow", and v2 is unsafe because a failure leaves partial output. Use a cloud committer (Lesson 14.3) or a table format. |
| spark.sql.files.maxRecordsPerFile | 0 (no limit) | Also a write option. Split files end in c000, c001. Each task sorts its rows by the partition columns before it writes. |
| spark.sql.sources.partitionOverwriteMode | static | dynamic replaces only the partitions in the new data. |
The long form of a read is spark.read.format('csv').option('header', True).load(path). A path can be a file, a folder or a pattern such as landing/orders/*.csv.
What changed at SwiftKart
The nightly job now reads the order lines with a DDL schema, so unit_price is a number from the first line. A rerun of one day replaces that day only. Tess's dashboard shows $89.00 again.
Most Databricks teams write Delta tables instead of plain Parquet: df.write.format("delta").mode("overwrite").saveAsTable("silver.orders"). Delta keeps a transaction log, so a failed write leaves no half-written files, the schema is enforced on every write, and MERGE replaces the append-or-overwrite choice (Module 13).
Next, Lesson 11.6: half the team writes SQL, half writes DataFrame code, and both run on one engine.
In one line
Give the schema when you read, pick the save mode by asking what a rerun does, and write one task per day folder so a rerun replaces only its own day.
Interview corner
What are Spark's save modes, and which is safe to rerun?
errorifexists (the default) fails if the path exists, overwrite replaces it, append adds rows, and ignore skips the write. Overwrite is idempotent but replaces the whole path unless partitionOverwriteMode is dynamic, in which case only the partitions in the new data are replaced. Append duplicates data on a retry, so it needs a dedup or a MERGE downstream.
Why not use inferSchema in production?
It needs an extra pass over the data, which is slow on big inputs, and its guess can change from one day to the next when an odd value appears, silently changing column types. An explicit schema is fast, documents the contract, and makes bad values visible as nulls (PERMISSIVE mode) or as a failure (FAILFAST).
How do you choose a partition column for written data?
Choose a column that most queries filter on and that has a modest number of distinct values, typically a date, sometimes a region. Each value becomes a folder, so a high-cardinality column such as a customer id creates huge numbers of tiny files, which slows every read and listing. Aim for files of roughly 100 MB to 1 GB each.
A daily job writes 6,000 tiny files per day, and on S3 it spends longer committing than computing. Explain both and fix them.
Every write task writes one file into each partition folder its rows touch, so 200 shuffle tasks over 30 days give 200 x 30 = 6,000 files; repartition by the partition column first (one task per day), and cap huge days with maxRecordsPerFile. The slow end is FileOutputCommitter v1: job commit renames every file out of _temporary, and on S3 a rename is a copy plus a delete, done file by file. Use a committer that avoids renames (EMRFS S3-optimized, S3A magic) or write a Delta or Iceberg table, whose commit is one atomic log entry; then compact with OPTIMIZE.