The file system

Programs that do anything useful tend to interact with the file system. They read input files, create output files, and organise results into directories. When we start generating real program output—such as HTML pages—we need a reliable way to work with paths, folders, and files on disk using Python’s standard library.

Working with file and directory paths

File system paths describe where files and directories live. Python provides tools that let us work with paths in a way that is clear and portable, without hard-coding platform-specific details.

A path can represent a file or a directory, and it can be absolute or relative to the current working directory. Treating paths as objects rather than raw strings makes them easier to combine and inspect.

from pathlib import Path

output_dir = Path("site")
index_file = output_dir / "index.html"

Checking whether files and directories exist

Before reading from or writing to disk, it is often useful to check whether something already exists. This lets a program make simple decisions based on the current state of the file system.

Python’s path objects can tell us whether they point to an existing file or directory.

from pathlib import Path

path = Path("site/index.html")

if path.exists():
    print("File already exists")

Creating directories

Programs often need to create directories to hold generated output. This is especially common when producing multiple files or organising results by category.

Python can create directories directly, including any missing parent directories along the way.

from pathlib import Path

output_dir = Path("site")
output_dir.mkdir(exist_ok=True)

Listing files in a directory

Once files exist on disk, we may want to see what is inside a directory. Listing files allows a program to process existing content, update generated output, or report what it has produced.

Python can iterate over the contents of a directory in a straightforward way.

from pathlib import Path

for path in Path("site").iterdir():
    print(path.name)

Combining file system operations with file reading and writing

File system operations rarely stand alone. In real programs, they are usually combined with reading and writing file contents as part of a larger task.

For example, a program might ensure a directory exists, build a path, and then write generated HTML to a file.

from pathlib import Path

output_dir = Path("site")
output_dir.mkdir(exist_ok=True)

page_path = output_dir / "mars.html"

html = "<h1>Mars</h1>"

with page_path.open("w") as file:
    file.write(html)

Conclusion

At this point, we know how to work with paths, check for existing files and directories, create folders, list directory contents, and combine these steps with file reading and writing. That is enough to orient us to how Python programs interact with the file system and to start producing structured output on disk with confidence.