File I/O (short for file input/output) is how a program reads data it didn't create and saves data that has to outlive it. In challenges it's the first thing every solution does: the puzzle input arrives as a file, and nothing else happens until it's been read and parsed. Binary files, such as executables, captured packets and memory dumps, are read the same way, just as bytes instead of text.
Before we read files, it's important to cover the file modes. These are characters that represent how we can interact with the file. Allowing and denying certain permissions is essential to security when handling files; this ensures data is not accidentally overwritten, read when unauthorized, or changed.
Several modes are used to open a file. These are:
r: Read Only. This only allows us to read data.w: Write Only. This allows us to write data to the file. This overwrites all existing contents and starts writing from the beginning of the file.a: Append Write. This starts writing from the end of the file but still does not allow read access.x: Exclusive Create. Like w, but raises FileExistsError instead of overwriting a file that already exists.Two additional modes provide us with compound permissions.
r+: Read and write access. The file's contents are preserved since r is the primary mode.w+: Write and read access. Since write is the primary mode, the file's contents are truncated.a+: Append and read access. Writes always go to the end of the file.rw, ra, and aw are all invalid modes. The one exception is adding b for binary files, as in rb or wb.These file modes are consistent across most languages. They are important to understand, and you should apply the Principle of Least Privilege when choosing a file mode.
The built-in open() function opens a file and returns a file object:
1f = open("input.txt", "r")
2data = f.read()
3f.close()The first argument is the file's path, and the second is the mode, which defaults to r. The file object isn't the file's contents; it's a handle that the methods below read from and write to. When you're done, close() releases the file. A relative path like "input.txt" is looked up in the current working directory, the directory you ran python3 from, not the directory the script lives in.
Text files are decoded from bytes into a str as they're read. The encoding defaults to your system's setting, which is UTF-8 on Linux and macOS but not always on Windows, so pass it explicitly when it matters: open("input.txt", encoding="utf-8").
Calling close() by hand is easy to forget, and if an exception is raised between open() and close(), the close() never runs. An open file keeps holding an operating-system resource until it's closed, and data written to it may not reach the disk.
The with statement solves this. It opens the file, binds it to the name after as, and closes it automatically when the indented block ends, even if the block raises an exception:
1with open("input.txt") as f:
2 data = f.read()
3
4# f is closed hereThis is how files should almost always be opened in Python, and the rest of this lesson uses it throughout. One with can open several files at once, separated by commas:
1with open("input.txt") as src, open("output.txt", "w") as dst:
2 dst.write(srcwith isn't specific to files: it works with any object that defines __enter__ and __exit__ methods, and Classes & Objects shows how to write your own.
A file object offers several ways to read, depending on whether you want the whole file at once or a line at a time:
f.read() returns the entire file as one string.f.readline() returns the next line, including its trailing \n, or an empty string at the end of the file.f.readlines() returns a list of every line, each still ending in \n.Suppose input.txt holds three lines:
110 20
230 40
350 60Each approach reads it like this:
1with open("input.txt") as f:
2 f.read() # Return: '10 20\n30 40\n50 60\n'
3
4A file object remembers its position, so each read continues from where the last one stopped. Once you've read to the end, further reads return an empty string until you reopen the file or move back with f.seek(0).
The trailing \n on each line is the most common source of parsing bugs: "80\n" == "80" is False. There are two easy ways to get rid of it. read().splitlines() splits the whole file into lines with the newlines removed, and line.strip() removes them from one line at a time:
1with open("input.txt") as f:
2 lines = f.read().splitlines() # lines = ['10 20', '30 40', '50 60']
Looping over the file directly reads one line at a time, so it works on files far larger than your memory. For challenge input, which is usually small, reading everything at once and splitting is often simpler.
Most puzzle input comes in a handful of shapes, each with a short idiom. These assume text holds the file's contents from f.read():
1nums = [int(line) for line in text.splitlines()] # one number per line
2rows = [The blank-line case is worth a second look: splitting on "\n\n" separates the blocks, and strip() first removes the final newline so the last block doesn't end with an empty line. When a line's format is more irregular than split() can handle, use regular expressions.
Opening a file with w creates it, or empties it if it already exists. Opening it with a adds to the end instead. write() takes a string and writes it as is; unlike print(), it doesn't add a newline, so include \n yourself:
1with open("results.txt", "w") as f:
2 f.write("port 22 open\n")
3 f.write(print() can also write to a file through its file argument, which adds the newline and converts non-string values for you:
1with open("results.txt", "a") as f:
2 print("port", 443, "open", file=To write many lines at once, join them: f.write("\n".join(lines) + "\n").
w empties the file the moment it's opened, before you write anything. Opening the wrong file in w mode destroys it. Use x when you mean to create a new file and want an error instead of an overwrite.Adding b to the mode opens a file in binary mode: no decoding, no newline handling, just the raw bytes. Reading returns bytes instead of str, and writing requires bytes:
1with open("/bin/ls", "rb") as f:
2 magic = f.read(4)
3
4f.read(n) reads at most n bytes, which is how you read a binary file in fixed-size pieces. f.seek(offset) jumps to a byte offset, and f.tell() reports the current one. Together they let you read a field from the middle of a file without reading everything before it:
1import struct
2
3with open("/bin/ls", "rb") as f:
4 f.seekThe trailing comma in entry, = unpacks the one-item tuple that struct.unpack always returns.
Binary formats are often a sequence of fixed-size records. Reading one record at a time until read() comes back short is the standard loop. Here, each record is a 4-byte ID followed by a 2-byte port, little-endian:
1import struct
2
3RECORD = struct.Struct("<IH")
4
5with open(struct.Struct compiles the format once, which is handy in a loop, and .size gives its length in bytes. The := operator, nicknamed the walrus, assigns chunk and tests it in the same expression, so the loop stops when read() returns an empty bytes at the end of the file. The struct section of Bytes & Encoding covers format strings in full.
To change bytes in a binary, read the whole file into a bytearray, modify it, and write it back out, usually to a new file so the original stays intact:
1with open("chall", "rb") as f:
2 data = bytearray(f.read())
Flipping a single conditional jump this way is a classic first patch in reverse engineering, as covered in RE: Static Analysis.
The pathlib module represents file paths as objects, which is tidier than building strings by hand. A Path can read or write a whole file in one call, which is handy for quick scripts:
1from pathlib import Path
2
3text = Path("input.txt").read_text()
4data = Path("chall")Paths join with the / operator, and have methods for the questions you'd otherwise ask the operating system:
1from pathlib import Path
2
3here = Path(__file__).parent # the directory this script is in
4inp = here /Path(__file__).parent / "input.txt" is a reliable way to find a file that sits next to your script, no matter which directory you run it from.