Files (in programming)
In short: From a program’s perspective, an object through which a program interacts with a file in the file system — creating, reading, writing, or deleting it.
In more detail: Access to files happens via I/O streams — data streams over which reading or writing happens byte by byte or character by character. Because file operations depend on external factors (file doesn’t exist, no permission, storage full), they often trigger exceptions and should be handled accordingly, or cleanly closed again with try-with-resources.
In Depth
The most important difference from variables in working memory: a file sits on a physical storage device and doesn’t “belong” exclusively to your own program — other processes can read, change, move, or delete it at the same time, the operating system can deny permissions, and the storage device can be full or unreachable (e.g. for network drives). This is why practically every file operation is a potential source of error that has to be handled in the code — unlike, for example, setting a local variable, which can almost never fail.
A typical, robust flow for handling a file:
try:
with open("configuration.txt", "r") as file:
content = file.read()
process(content)
except FileNotFoundError:
print("File does not exist.")
except PermissionError:
print("No read permission.")
# "with" automatically closes the file, even on an exception
# - the same principle as try-with-resourcesFiles are almost never read or written completely “in one go” (that would be memory-hungry for large files), but via I/O streams — a continuous flow of data that’s read or written step by step (byte by byte or character by character, or in blocks). The operating system internally manages a “file pointer” (cursor) for this, which remembers at which position in the file the next read/write access takes place.
A central principle when working with files: every opened file has to be closed again. As long as a file is open, the operating system holds a limited resource for it (a “file handle”) — if closing is forgotten, these resources eventually run out, and buffered write data that hasn’t yet been physically saved can even be completely lost. try-with-resources (or the with statement in Python) reliably automates this closing, even if an exception occurs during processing.
See also: I/O Streams, try-with-resources, Read Files, Write Files