File paths#

Handling file paths is one of the maybe not-so-fun parts of a scientist’s job. But we have to work with file paths all the time, e.g., to read in data files, write new data files, or save the plots we created.

Technically, you could simply use everything we learned about string formatting to manually create a file path, e.g., the file where want to save your new figure:

figure_directory = '/home/username/my_figures/'
figure_temp = figure_directory + 'temp_timeseries.png'
print(figure_temp)
/home/username/my_figures/temp_timeseries.png

The problem will occur when you want to run your code on different platforms, e.g., Windows and Linux since Windows uses backslashes and Linux forward slashes for file paths. For this reason, you should never hardcode your file paths, but rather use one of the existing packages for handling file paths.

pathlib#

pathlib is the current standard for handling file paths. To concatenate the components of the path with pathlib, we first have to create a Path object:

from pathlib import Path

data_directory = Path('/home/username/my_data/')
print(data_directory)
type(data_directory)
/home/username/my_data
pathlib.PosixPath

Now we can simply use forward slashes to concatenate the components of our file path, which is a very intuitive way. Always use forward slashes, pathlib will take care of the rest.

file_temp = data_directory / 'data_temp.csv'
print(file_temp)
type(file_temp)
/home/username/my_data/data_temp.csv
pathlib.PosixPath

The old way: os.path#

The os.path module is still used a lot to handle file names. It includes the method join() which allows you to build platform-specific file paths.

import os.path

figure_temp = os.path.join(figure_directory, 'temp_timeseries.png')
print(figure_temp)
/home/username/my_figures/temp_timeseries.png

In contrast to pathlib, os.path.join does not create a Path() object, but a string.

type(figure_temp)
str

For some additional information, you can read this short blog post which is a good entry-level tutorial to path handling.

Take home: path handling#

  • Never use + and other string shenanigans to handle your file paths.

  • pathlib is the current standard. It provides a very intuitive way of path handling once you get used to it.

  • os.path and, in particular, os.path.join is another simple way to deal with paths as strings.