Skip to content

Handling File Paths in Python

When you grab a file path from the file explorer, you get a path with backward slashes (in Windows). However, you can’t just copy and paste that file path into Python because backslashes are escape characters in Python, which are only used to insert “illegal” characters. For a quick explanation on escape characters, click on the link just above. W3School has a great example.

If you try to use backslashes, you’ll get this error – “unicodeescape codec can’t decode bytes in position”.

Fortunately, there are a few options for working around backward slashes.

Raw Strings

Instead, use raw strings by prefixing the string with “r”. By doing this, you can use the “normal” file path with back slashes.

path = r"C:\Users\YourName\Documents"

Forward Slashes

Python can handle forward slashes in file paths, and so it is often just easier or more convenient to replace the backward slash with a forward slash rather than deal with strings.

path = "C:/Users/YourName/Documents"

Pathlib Module

You can also use the pathlib module to work with file and directory paths. This option might not seem all that inticing, but there are other cool things you can do with pathlib, so it might be worth looking into.

from pathlib import Path
path = Path("C:/Users/YourName/Documents")

Happy coding!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.