HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

3) File Input/Output Lesson

Python Path and pathlib

7 min to complete · By Martin Breuss

What is the Python Path

In the previous examples, you've referenced the files you're opening and closing by their names. This only works if the files are in the same folder as the Python script you're running. When you're referencing files like this, you're using their relative path:

with open("input.txt", "r") as file_in:
    print(file_in.read())

The relative path of a file is the path from the Python script to the file.

An alternative way to reference a file is by using its absolute path. If you change the previous example to use the absolute path, it could look something like this, depending on where the file is located on your system:

with open("/Users/yourname/Desktop/input.txt", "r") as file_in:
    print(file_in.read())

When you use the absolute path of a file, you can run the Python script anywhere on your machine, and it will find the file input.txt in the folder /Users/yourname/Desktop and be able to open it up.

Python Pathlib: Better Path Handling

File paths are a tricky subject. One reason is that it might be hard to keep track of the exact absolute path of a file. Most of all, however, they are handled differently by different operating systems. Windows paths look completely different than UNIX paths, so if you write a script that works with UNIX style paths, half of your users would probably not be able to use it.

There are, of course, clever ways around this challenge, and the most straightforward one is using Python's pathlib module. You've worked with it before in the previous module of this course, and now you'll apply it to File Input/Output.

from pathlib import Path

data_path = Path("/Users/yourname/Desktop")

with open(data_path.joinpath("input.txt"), "r") as file_in:
    print(file_in.read())

You've imported Path from pathlib and used it to create a Path() object that points to the folder location where your data is located. You saved this information in the variable called data_path.

Colorful illustration of a light bulb

Info: This is an improvement over using relative or absolute paths because this code is operating-system agnostic, which means it'll work the same on Windows and UNIX machines.

After defining your data_path, you can use it as usual inside your context manager, where you're providing the file name. With .joinpath(), you're adding the file name to the Path() object, which provides open() with the location of the file you want to open. The rest of the code stays exactly the same.

Shortcuts To Opening Files

The pathlib module and the Path() objects provide you with a couple of convenient shortcuts. While you can open and read a file as you did above, you can do it even faster when using methods on your Path() objects:

from pathlib import Path

filepath = Path("/Users/yourname/Desktop/input.txt")

with filepath.open() as f:
    print(f.read())

You can use .open() on a Path() object to open the file in the same way as you would when using Python's built-in open().

You can also read from and write to files with quick Path() methods:

from pathlib import Path

p = Path("hello.txt")
p.write_text("Hello world!")
p.read_text()  # OUTPUT: "Hello world!"

pathlib is a great module that makes working with File Input/Output faster and more secure.

Practice reading and writing to files with your lab exercises, and think about something you'd like to build that involves reading from and writing to files. Take a note in your journal to keep track of your ideas.

In the next section of this module, you'll learn more about functions, a structure that you've already used before. You'll learn what functions are, why they are useful, and how you can write your own functions.

Colorful illustration of a light bulb

Additional Resources

Summary: What is the Python Path

  • You can reference the location of a file in two ways:
    1. Relative path: This is the location, as seen from the directory, that your Python script executes from.
    2. Absolute path: This is the location from the root directory of your operating system.
  • You can use the pathlib module and work with Path() objects instead of plain strings. This has the advantage that it makes your paths operating system agnostic, and you can use the many convenience methods that the module provides to speed up and simplify your File I/O tasks.