Processing large files with Python
Recently, a co worker of mine was trying to load a very large file from an SFTP server into PostgreSQL. Using psycopg2 they were leveraging the standard COPY FROM capability to load the file directly into a temporary table they had created.
Their code was something like this relatively standard approach (generated by ChatGPT):
def copy_file_to_table(file_path, table_name, connection):
with connection.cursor() as cursor:
with open(file_path, 'r') as f:
cursor.copy_expert(f"COPY {table_name} FROM STDIN WITH CSV HEADER", f)
connection.commit()
# Example usage
file_path = './your/file.csv'
copy_file_to_table(file_path, table_name, conn)Unfortunately, with only a 500MB file, the process failed repeatedly, either running out of memory or timing out.
- Perhaps there may not be enough server memory, or
- maybe not enough laptop memory, or
- perhaps it was a problem with the remote VPN connection we are required to use when connecting to the database directly.
Regardless, the process did not work even for a small half gigabyte file. If the data vendor sends us a much larger file — say 2 or 3TB — the process will definitely not work!
This is not the first time in my career I’ve needed to process large data files, so I thought I would write this blog post to address how I like to do it.
Example
Unfortunately, I can’t use the proprietary data file from work, so let us instead imagine that we have a collection of data files in S3. Each data file will be a gzipped .json file that contains an array of colour data, something like this:
[
{
"id": "25a134d3-64fe-45a7-9ce9-948a4d1e17bb",
"name": "Pumpkin",
"base": "orange",
"hex": "#F5761A",
"rgb": [
245,
118,
26
]
}
]Our initial business logic will simply be to collect all of the colours across all of the data files that are “reddish” (where their red value is greater than their green or blue value).
Obviously, in the real world we would be dealing with significantly more complex data and logic. But for this example, I want to focus on flexibly processing large amounts of data — not the data itself or specific business logic.
Reading many files from S3, un-zipping them, parsing them, and filtering them is obviously more complex than “just load a .csv file into PostgreSQL”, but the same techniques can be used for both, and will let us explore additional ideas along the way.
Requirements
While my coworker waspulling the file from an SFTP server, in the future we might want to pull from an S3 bucket instead. So our first requirement is that the data source should be easy to change without impacting most of our code.
At a previous job I needed to read a collection of thousands of smaller files (only 1–10 megabytes each) from an S3 bucket, joining them all together to perform analytics on the data. It is not uncommon to require data validation or transformations before loading the data into our database, so our solution must support these types of data transformations and analytics.
My coworker needs to process a .csv file. However, I’ve often needed to process .json files instead. Ideally we could quickly whip up a data processing solution for either file format without too much concern.
We also want confidence that our code works, before we try processing terabytes of remote data (over slow VPNs). So we definitely want to test our code before we start it on the real data.
So, here’s our list of requirements:
- Easily change the data source without impacting the rest of our code
- Enable data transformations or analytics over the data
- Separate the file format from the data processing logic
- The code should be easy and fast to test locally
A first attempt
Here is how we might traditionally have solved this problem using a simple imperative programming approach.
def traditional_approach(
s3, # type: ignore
bucket_name: str,
prefix: str,
):
# List the objects in our S3 Bucket
s3_response: dict[str, Any] = s3.list_objects_v2(
Bucket=bucket_name, Prefix=prefix
) # type: ignore
# Iterate through each object in the response
for obj in s3_response.get("Contents", []): # type: ignore
# Get the object key (i.e., file path)
key: str = obj.get("Key")
# Skip directories - we only process files directly where we're told to
if key.endswith("/"):
continue
# Download the given file
print("Downloading file: ", key)
obj_response = s3.get_object(Bucket=bucket_name, Key=key) # type: ignore
content: bytes = obj_response["Body"].read() # type: ignore
# Decompress and parse the JSON .gzip data file
json_data: dict[Any,Any] = json.loads(gzip.decompress(content))
# Process our JSON data
for entry in json_data:
rgb = entry["rgb"]
# Determine if the colour is reddish
is_reddish = rgb[0] > rgb[1] and rgb[0] > rgb[2]
if is_reddish:
print( entry )
traditional_approach(s3, BUCKET_NAME, FILE_PREFIX)This code works, but it fails almost every requirement we gave ourselves!
This one function is responsible for listing the files in the S3 bucket, downloading the files, decompressing the files, parsing the files, and processing the data! Thus, it violates both the Single Responsibility Principle (SRP) and the Open/Closed Principle.
The cost of violating these principles is that the code is not reusable or testable!
- To modify the data source, use it to perform different business logic, or change the file format, we need to modify this function. The code can only be reused by copying and pasting everything into a new function and modifying it. Very disappointing!
- Similarly, with all of the logic in one function, it is very difficult to test! We would need to mock out the S3 API, the gzip API, and the JSON API just to test this one function, or run it against a MinIO bucket with docker-compose, or even worse, run it against the real S3 bucket. Worse, before we can test the business logic, all the other logic must be working correctly.
A better approach
Let us rebuild this with a domain-driven functional approach.
(Don’t worry; we’re not going to do hard-core functional programming — just the “good parts” version.)
For our purposes, functional programming just breaks down our problem into a set of small hopefully reusable functions. The only data the function uses is passed in as arguments, and the only data the function returns is the result. Our functions will not access any global variables or modify any global state.
When we consider our domain of colour, It makes sense to build a small data class to hold a single colour. Another aspect of functional programming is not changing data in place, so I’m going to make this small data class immutable. (by setting frozen=True in the @dataclass decorator).
@dataclass(frozen=True)
class ColourId:
"""A very small data class that holds a colour name and details."""
id: str
name: str
base: str
hex: str
rgb: tuple[int, int, int]Let us also write our very simplistic “business logic”:
def is_colour_reddish(colour: ColourId) -> bool:
return colour.rgb[0] > colour.rgb[1] and colour.rgb[0] > colour.rgb[2]Helper functions
Now let us write some small helper functions.
Each function will do exactly one task, following the Single Responsibility Principal.
Additionally, this collection of small helper functions can be easily reused in future data pipelines that we will want to build — Even though we don’t have the current requirements for those future data jobs. Thus, we are also following the Open/Closed principle of development — open for reuse, closed for modification because there is no need to modify these small but still useful “atomic” functions.
Finally, I am going to use generators (called iterators or enumerators in some languages).
Generators
A quick discussion about generators.
First generators are really cool.
They are a way to create a stream of data values without having to store everything all in memory at once. They work very nicely with the for in loop in Python. Let's take a look at a trivial example of a python generator function:
def generator_example( ) -> Generator[str, None, None]:
yield "Good"
yield "Morning"
yield "World"
yield "!"The yield keyword is what makes this function a generator. Technically, when the function is called it returns a generator object, which can be iterated over. Fortunately, Python makes this easy by allowing you to use a for in loop directly on the generator object:
for word in generator_example():
print(f"> {word}")unsurprisingly returns:
> Good
> Morning
> World
> !What’s cool about generators is that they can be infinite! They can also be used to lazily load data from a file or a network connection. This is very useful when you have a large amount of data that you don’t want to load it all into memory at once!
For example, ChatGPT easily made a generator that can calculate the digits of pi to any precision you want.
def pi_digits():
"""Generator to return digits of π one by one."""
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
if 4 * q + r - t < n * t:
yield n
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k + 2) + r * l) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nrWe don’t need to worry about the details of the pi_digits() generator, but it is a good example of how powerful generators can be. Note the yield statement in the middle of the while True loop.
Here’s a simple example of how we might use the pi_digits() generator:
counter = 0
for digit in pi_digits():
print(digit, end="")
counter += 1
if (counter==1):
print(".", end="")
if counter > 100:
breakThis returns 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
exactly as you would expect. I had to add the counter to exit after 100 digits, otherwise it would still be chewing up my CPU cycles endlessly generating digits! The pi_digits() function will run as long as we want, happily generating the digits of Pi. Note though that we're not storing all the digits in memory at once, but instead generating them one by one as needed! The caller of the generator function is in control of how many digits are generated.
You can think of it as a “sequence” of digits streaming out of our generator function that we can easily loop over, pulling out the digits one by one as we need them.
However, the above code to using the pi_digits() generator is actually a little more complex than I would like. Fortunately, there’s a more elegant way of working with generators called seq (short for "sequence"), which is part of the very helpful pyfunctional library:
from functional import seq # pyfunctional library
for digit in seq(pi_digits()).take(1_000):
print(digit, end="")We can pass our generator to the seq function, which converts it into a very helpful Python "data sequence". The data sequence has a whole bunch of useful functions, such as the take() function I'm showing here to "take" just the first 1,000 digits of Pi. Once we have a sequence of data, we can easily take, transform, filter, or map reduce the sequence as we need to.
For example, we could filter() out all the digits that are less than 3 with a simple lambda, and THEN take the first 10 remaining digits of Pi:
digits = (
seq(pi_digits())
.filter(lambda x: x >= 3)
.take(10)
)
for digit in digits:
print(digit, end="")Which returns the odd sequence: 3459653589.
Get Robert McCarter’s stories in your inbox
Join Medium for free to get updates from this writer.
Just as important, we can transform the data in the data sequence with the map() function. For example, we could subtract 1 from each digit of Pi (why?! Why not?!):
digits = (
seq(pi_digits())
.filter(lambda x: x >= 3) # filter keeps values where the function returns True
.map(lambda x: x - 1) # map calls the function with each value, and keeps the new value
.take(10)
)
for digit in digits:
print(digit, end="")Which of course prints 2348542478.
Of course, we don’t need to use lambda functions. I am above because they are very small and easy to understand. We could easily use named functions instead:
def greater_than_equal_to_three(x: int) -> bool:
return x >= 3
def subtract_one(x: int) -> int:
return x - 1
digits = (
seq(pi_digits())
.filter(greater_than_equal_to_three) # filter keeps values where the function returns True
.map(subtract_one) # map calls the function with each value, and keeps the new value
.take(10)
)
for digit in digits:
print(digit, end="")Does exactly the same thing as the example with lambda functions, and is perhaps a little more readable.
Alright — one last idea about sequences before we move on. All of these examples so far have been with an infinite sequence of numbers (from Pi) one digit at a time. However, we could just as easily return strings, or lists, or any other data type from our generator functions. For example, we could have our generator return arrays:
def generate_arrays() -> Generator[list[int], None, None]:
for i in range(1,11,3):
yield [i, i+1, i+2]We could even turn this BACK into a sequence of just numbers with the built-in flatten() function:
values = seq(generate_arrays()).flatten()
for digit in digits:
print(digit, end=", ")Prints out: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.
Visually we’ve done this:
All of this code is very functional and I think very Pythonic. I hope you can see how powerful generators can be when combined with the seq() function from the pyfunctional library.
You can now probably see where I’m going with this, and why generators are so useful for processing large data files. Let’s get back to our original problem…
Back to the challenge of elegantly processing large files
Recall that we have a collection of gzipped JSON files in an S3 bucket, and we want to process all of the JSON colour entries in those files to find the “reddish” ones.
The first thing we need to do is list all of the files in the S3 bucket that we want to process:
def list_s3_bucket_file_keys(
s3, # type: ignore
bucket_name: str,
prefix: str,
) -> Generator[str, None, None]:
"""Returns a generator of file names (technically S3 bucket keys) from the given S3 bucket
that have the given path prefix.Args:
s3: The boto3 S3 client object
bucket_name (str): The name of the S3 bucket to retrieve data from
prefix (str): The "file path" prefix of the files (S3 bucket keys) to be returned.
So all file paths returned from this function will have this prefix.
Yields:
Generator[str, None, None]: A sequence of matching file names (S3 bucket keys).
"""
# List all objects in the bucket with the specified "file/folder" prefix
# See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/list_objects_v2.html
response: dict[str, Any] = s3.list_objects_v2(
Bucket=bucket_name, Prefix=prefix
) # type: ignore
# Iterate through each object in the response
for obj in response.get("Contents", []): # type: ignore
# Get the object key (i.e., file path)
key: str = obj.get("Key")
yield key
Aside: I strongly prefer to strongly type my Python code, but with the S3 Boto3 library that often means I need to use the
# type: ignorecomment. This tells the type checker in my IDE to ignore missing types on that line of code. This is unfortunate, but I still think the benefits of strong typing outweigh the inconvenience and slight ugliness occasionally ignoring unavoidable type errors with non-typed libraries.
This function is a generator that yields the keys of all the files (with our given prefix) in the S3 bucket. That is all it does — following the Single Responsibility Principle.
We can reuse this function in our future data pipelines to process any number of files in an S3 bucket. So this code is open for reuse, but closed for modification, and much more flexible than our previous attempt!
Given that it’s sole job is accessing S3, it’s still tricky to test. But we can test it, either by running it against a MinIO bucket with docker-compose, or by running it against a real but test S3 bucket. In our toy “colours” example case here, I’m just going to run it against the real S3 bucket. If you’re interested, I can write about how to test this with Testcontainers in a future blog post.
Now that we have a generator that yields the keys of all the files in the S3 bucket, we need to write a function to download each file from S3.
But instead of downloading ALL the files, we’ll write a function that downloads just a single file, again following the Single Responsibility Principle and trying to make it as reusable as possible:
def download_s3_file(s3, bucket_name: str, key: str) -> bytes: # type: ignore
"""Download the given file (S3 bucket key) from S3 and return the raw bytesArgs:
s3: The boto3 S3 client object
bucket_name (str): The name of the S3 bucket to retrieve data from
key (str): The S3 key (file name if you will) of the object to download
Returns:
bytes: The raw bytes of the given file from S3
"""
assert not key.endswith('/'), f"Key {key} is a directory, not a file"
obj_response = s3.get_object(Bucket=bucket_name, Key=key) # type: ignore
content: bytes = obj_response["Body"].read() # type: ignore
return contentWith these two functions, we can now list all the files in the S3 bucket and download them one by one:
We can use the map() function that we used before to subtract 1 from each digit of Pi. This time we will map() with the download_s3_file() function, apply it to each file name key returned by list_s3_bucket_file_keys() generator.
One small thing — we need to exclude directories from our list of files. Of course we could do this in the list_s3_bucket_file_keys() function, but I think it's better to keep that function as simple as possible. In the future perhaps we want to process directories! Instead we can use the filter() function from the pyfunctional library to filter out any keys that end with a / character:
result_so_far = (
seq(list_s3_bucket_keys(s3, BUCKET_NAME, FILE_PREFIX))
.filter(lambda key: not key.endswith("/")) # ignore directories
.map(lambda key: download_s3_file(s3, BUCKET_NAME, key))
)So now we have a sequence of raw bytes from each file in the S3 bucket. Remember that in our imaginary example, each file is a gzipped JSON file, so our next step is to decompress the data and parse the JSON.
Fortunately, Python already has a built-in gzip library that can decompress the data for us. Indeed, it has a function that takes a byte array and returns a byte array of the uncompressed data! It is the gzip.decompress() function. Using it, our data pipeline now looks like this:
result = (
seq(list_s3_bucket_keys(s3, BUCKET_NAME, FILE_PREFIX))
.filter(lambda key: not key.endswith("/")) # ignore directories
.map(lambda key: download_s3_file(s3, BUCKET_NAME, key))
.map(gzip.decompress)
)So now we have a sequence of decompressed JSON files from our S3 bucket. We want to read each decompressed JSON file and return a normal Python list that represents the JSON colour data in that file.
The json.loads() function can do this for us easily enough, and another map() function will do the trick:
result = (
seq(list_s3_bucket_keys(s3, BUCKET_NAME, FILE_PREFIX))
.filter(lambda key: not key.endswith("/")) # ignore directories
.map(lambda key: download_s3_file(s3, BUCKET_NAME, key))
.map(gzip.decompress)
.map(json.loads)
)Now every item in our data sequence is a Python list of colour dictionaries. But we don’t want a data sequence of lists, we really just want a data sequence of colour JSON objects, which should be much easier to work with.
The flatten() function I introduced above (from the pyfunctional library) can do this for us:
result = (
seq(list_s3_bucket_keys(s3, BUCKET_NAME, FILE_PREFIX))
.filter(lambda key: not key.endswith("/")) # ignore directories
.map(lambda key: download_s3_file(s3, BUCKET_NAME, key))
.map(gzip.decompress)
.map(json.loads)
.flatten()
)Okay, now we have a sequence of colour dictionaries, which is great but not as nice as if we had a sequence of ColourId objects - our domain data class from so far above.
Let’s write a small “Data access layer” function to help us convert from our JSON:
def create_colour_from_json(data: dict[str, Any]) -> ColourId:
return ColourId(
data["id"],
data["name"],
data["base"],
data["hex"],
data["rgb"],
)Easy enough, and obviously easy to test too. Now we can use the map() function to convert our JSON data into our ColourId domain class:
result: list[ColourId] = (
seq(list_s3_bucket_keys(s3, BUCKET_NAME, FILE_PREFIX))
.filter(lambda key: not key.endswith("/")) # ignore directories
.map(lambda key: download_s3_file(s3, BUCKET_NAME, key))
.map(gzip.decompress)
.map(json.loads)
.flatten()
.map(create_colour_from_json)
)Finally, we can apply our filter “business logic” to filter out anything that is not “reddish” in colour:
result: list[ColourId] = (
seq(list_s3_bucket_keys(s3, BUCKET_NAME, FILE_PREFIX))
.filter(lambda key: not key.endswith("/")) # ignore directories
.map(lambda key: download_s3_file(s3, BUCKET_NAME, key))
.map(gzip.decompress)
.map(json.loads)
.flatten()
.map(create_colour_from_json)
.filter(is_colour_reddish)
)
for colour in result:
print(colour)So now we have a sequence of ColourId objects that are "reddish" in colour, loaded from an S3 bucket of gzipped JSON files, where we only downloaded one file at a time.
Summary
I think that data pipeline is much more elegant and reusable than our first attempt!
So what did we do?
- We built ourselves a small “domain logic layer” consisting of an immutable data class to hold our colour data, and a small bit of business logic to determine if a colour is “reddish”.
- We built some generic functions to list the files in an S3 bucket and download a file from an S3 bucket These functions are not tied to any specific business logic or file formats, and could easily be reused in future data pipelines.
- We built ourselves a small “data access layer” that was just a single function to convert a JSON dictionary into our domain data class.
With this small set of functions, we were able to build a data pipeline that processed a collection of .json.gz files sitting in an S3 bucket. I think that it is pretty easy to read through the code and understand this data pipeline.
It is very declarative — we’re clearly listing out the steps in our data pipeline, and each step is a small, reusable function — often directly from the Python libraries — that does one thing, and does it well.
How does it compare to the requirements we set out at the beginning?
- Easily change the data source without impacting the rest of our code
- Enable data transformations or analytics over the data
- Separate the file format from the data processing logic
- The code should be easy and fast to test locally
Unsurprisingly, our code meets all of these requirements!
All of our code is highly functional, but that’s really just a byproduct of following the Single Responsibility Principle and the Open/Closed Principle in a domain-driven development approach.
And our solution is highly flexible. We can easily change the data source by changing the list_s3_bucket_keys() function. Indeed, when I was testing this code, I was able to switch between a real S3 bucket and some files in a local directory by just changing the first 3 lines of code in the pipeline.
Similarly, if we had files that were zipped instead of gzipped, we could replace the gzip.decompress with zip file solution.
Going from .json to a .csv file could be done by changing the json.loads function to a CSV parser.
Our business logic is all in pure function with zero dependencies on external services (such as the data access layer, the data pipeline, or the S3 API). This makes our core business logic code easy to test.
We could easily introduce additional business logic functions, and build new data pipelines without touching any of our existing code.
Our S3 functions are of course a little trickier to test, but we can easily run them against a MinIO bucket, and we can test them without needing to run the entire data pipeline, and separately from the business logic.
Thanks for reading this far! I hope you found this blog post useful, and can see the benefit of building data pipelines in this way.
The Jupyter Notebook I developed for this article is here: https://github.com/RobertMcCarter/blog-public/blob/main/2023-02-Python-process-large-files/python-process-s3-files.ipynb
You can actually run the Jupyter notebook here:
https://colab.research.google.com/github/RobertMcCarter/blog-public/blob/main/2023-02-Python-process-large-files/python-process-s3-files.ipynb





