Path

Resources

Paths

The location of a file in a file system is given by its path that is composed by its location in the directories, subdirectories and file name. Some examples of paths are: “c:\users\jane\documents\letter.doc”, “/users/jane/documents/letter.doc”, or “/home/jane/documents/letter.doc”.

One relevant difference between Windows and Unix-like (MacOS or Linux) operating systems is that in windows the path elements are separated by the “\” character, whereas in MacOS and Linux the separator is “/”. Python is a multiplatform language, but we have to take into account these details if we want to write software capable of running in different operating systems.

Path objects

In Python we could use strings to store path information and, in fact, that used to be the case, but now it is very common to work with Path objects available in the pathlib module. I would recommend to use these convenient objects instead of plain string objects.

One advantage of the Path objects is that we can join them together very easily.

The Path class some very convenient methods, like home that will give us the $HOME directory for the current user or cwd that will return the current working directory.

Paths objects have a rich functionality. For instance, we can check if they exist in the file system.

We can list the contents of a directory.

And we can get their names and suffixes.

We can also:

  • open a file using the open method of the Path objects
  • create a directory using mkdir
  • remove a file with unlink or a directory with rmdir.

In your home directory create a file named “hello.txt”, write in it the text “Hello world”, then get a directory listing and check that the file is really there, after that, open the file and read the text in it. Finally, remove the file and check that it has been really deleted.

Tip

¿Cuál es el directorio de trabajo actual? ¿Hay algún fichero en él? ¿Del primero de los ficheros que aparecen en el listado, cuál es la ruta completa? ¿Se podría extraer de esta ruta el nombre del directorio y el fichero? ¿Cuál es la $HOME de nuestro usuario? ¿Del fichero ‘programa.py’ cuáles son el nombre y la extensión?