avatarBetter Everything

Summary

The provided content is a comprehensive guide on handling file paths in Python, detailing the differences between absolute and relative file paths, offering solutions to common issues with backslashes in Windows file paths, and illustrating how to navigate the file system relative to a script's working directory.

Abstract

The article titled "Filepaths in Python — A Beginner’s Guide" serves as an educational resource for individuals looking to understand and manipulate file paths within Python scripts. It explains the concept of absolute file paths, which provide a full location from the root directory, and relative file paths, which are contextual to the script's location. The author addresses a common problem faced by Python developers on Windows systems: the incorrect interpretation of backslashes in strings. Solutions such as using forward slashes, escaping backslashes, and employing raw strings are presented. The guide also demonstrates how to append filenames to paths and how to utilize the os module to interact with the file system, including listing directory contents and opening files. Furthermore, the article clarifies how to reference files and directories at different levels of the file system hierarchy relative to the script's current working directory.

Opinions

  • The author emphasizes the importance of understanding file paths for file operations in Python, suggesting it is a fundamental skill for developers.
  • The guide suggests that Python's os module is essential for file and directory manipulation, implying its robustness and utility.
  • The article offers practical advice for Windows users, highlighting the system's peculiarities with backslashes in file paths and providing clear workarounds.
  • By providing examples of working with files in both higher and lower directories relative to the script's location, the author conveys the importance of a well-organized file system structure for Python projects.
  • The use of a real-world example with a structured directory layout helps readers visualize and understand the concepts being taught, which may indicate a preference for hands-on, example-based learning.
  • The author encourages readers to support the platform and themselves by becoming Medium members, which could suggest a belief in the value of the content provided and the platform's business model.
  • The inclusion of related articles at the end of the post indicates an intent to offer further reading and establish the author's expertise in the field of Python file manipulation.

Filepaths in Python — A Beginner’s Guide

Do you want to write data into a file or read data from a file? Or check what files and folders are in a certain directory? Python is well suited for all the above.

In order to work with a file or directory you have to know its name. But not only the name is important, you also have to know where the file or directory is stored. That place is specified with the path.

There are 2 types of filepaths:

  • Absolute filepaths describe the path from the root directory to the file.
  • Relative filepaths describe the path from the Python script to the file.

In this article I will tell you what I know about working with both types of filepaths so that you can easily work with files and directories as well.

Filepaths are used to describe where a file is stored. Image by catalyststuff on Freepik

Example Files and Directories

To be able to explain how filepaths work, I will first show you some files and directories on my computer that will serve as examples.

On the C drive of my computer there is a Users directory. In the Users directory there is a directory for each user. For example there is a directory called BE (for user BE).

In the BE directory there is a Documents directory and in the Documents directory I have prepared 5 directories:

  • Directory A Absolute filepath: C:\Users\BE\Documents\A Contains: Directory B and file 1.txt
  • Directory B Absolute filepath: C:\Users\BE\Documents\A\B Contains: Directory C and file 2.txt
  • Directory C Absolute filepath: C:\Users\BE\Documents\A\B\C Contains: Directory D and file 3.txt and Python script main.py
  • Directory D Absolute filepath: C:\Users\BE\Documents\A\B\C\D Contains: Directory E and file 4.txt
  • Directory E Absolute filepath: C:\Users\BE\Documents\A\B\C\D\E Contains: File 5.txt

All code in this article will be written in main.py which is stored in directory C.

Absolute filepaths and backslash trouble

If you want to use absolute filepaths, like the ones above, that is perfectly fine.

But working with filepaths that have backslashes (\) can cause trouble in Python. That has to do with the fact that backslashes are also used with escape characters.

import os

filepath = 'C:\Users\BE\Documents\A\B\C'

print(os.listdir())

The above code gives an error: SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2–3: truncated \UXXXXXXXX escape

Here are some solutions to avoid the problem:

  • use forward slashes instead of backward slashes: filepath = 'C:/Users/BE/Documents/A/B/C'
  • replace the backslashes with double backslashes filepath = 'C:\\Users\\BE\\Documents\\A\\B\\C'
  • use a raw string by putting an r before the string filepath = r'C:\Users\BE\Documents\A\B\C'

Adding filenames to filepaths

If you want to work with a file you can add the filename to the filepath with a slash in between:

filename = '3.txt'
filepath = 'C:\\Users\\BE\\Documents\\A\\B\\C\\' + filename

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

or

filename = '3.txt'
filepath = 'C:/Users/BE/Documents/A/B/C/' + filename

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

Relative filepaths and the working directory

When we work with relative filepaths it is important to understand that this is the path between the file and the location of the Python script.

The directory in which a script is placed is also known as working directory.

You can determine the current working directory in Python with the getcwd function form the os package.

import os

print(os.getcwd())

The above code correctly prints: C:\Users\BE\Documents\A\B\C

By default, Python uses the current working directory to look for directories and files. Here are 2 examples of that:

import os

print(os.listdir())

with open('3.txt') as f:
    print(f.read())

This prints:

['3.txt', 'D', 'main.py']
This is the content of 3.txt

We didn’t specify a directory when calling the listdir function and so it showed us the contents of the current working directory, which is C.

And when opening the file we only specified the filename 3.txt. Since we didn’t specify the filepath it looked for the file in the current working directory.

Relative filepaths to directories higher up

When talking about directories A and B, we could say they are ‘higher’ then our working directory C. A relative filepath would have 2 dots .. to specify to look 1 directory higher up.

And so print(os.listdir('..')) prints the content of directory B: ['2.txt', 'C'].

To open 2.txt we can use the following relative filepath: '../2.txt'.

with open('../2.txt') as f:
    print(f.read())

The above code prints: This is the content of 2.txt

If we want a relative filepath to A we would need to look 2 directories higher up. In that case the code would look like this:

import os

print(os.listdir('../..'))

with open('../../1.txt') as f:
    print(f.read())

This prints: ['1.txt', 'B'] and This is the content of 1.txt

Relative filepaths to directories deeper down

Instead of looking at directories higher up, we will now look at directories deeper down.

For example directory D is within directory C. A relative filepath to directory D from our working directory C would simply be: D.

print(os.listdir('D'))

with open('D/4.txt') as f:
    print(f.read())

The above code prints: ['4.txt', 'E'] and This is the content of 4.txt

And the relative filepath to directory E would be: D/E.

print(os.listdir('D/E'))

with open('D/E/5.txt') as f:
    print(f.read())

The above code prints: ['5.txt'] and This is the content of 5.txt

Thank you for reading!

You can get full access to all my posts by joining Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium:.

You might also like:

Python
Programming
Automation
Data Engineering
Software Development
Recommended from ReadMedium