rohrl77
rohrl77

Reputation: 3337

Absolute folder path in python

I cannot get this code to work for me:

import os

# Define folder to search
searchFolder = "C:\Users\rohrl\OneDrive\Python\PictureCompare\MixedPictures"
os.chdir(searchFolder)
print(os.curdir)

I keep on getting a Unicode error on line 4. What am I doing wrong? I'm on a Windows PC.

Upvotes: 0

Views: 727

Answers (2)

bitranox
bitranox

Reputation: 1894

You need to escape the backslash - or use slashes. Also I suggest You look at the pathlib Library (it does not help in this short example, but pathlib makes it more pythonic to work with file system objects) :

import os
import pathlib

# variant 1 - raw string
str_search_folder = r"C:\Users\rohrl\OneDrive\Python\PictureCompare\MixedPictures"
# variant 2 - escaping the backslash
str_search_folder = "C:\\Users\\rohrl\\OneDrive\\Python\\PictureCompare\\MixedPictures"
# variant 3 - my prefered, use slashes
str_search_folder = "C:/Users/rohrl/OneDrive/Python/PictureCompare/MixedPictures"

path_search_dir = pathlib.Path(str_search_folder)

os.chdir(path_search_dir)
# variant 1
print(os.curdir)
# variant 2
print(path_search_dir.cwd())

Upvotes: 1

Alan
Alan

Reputation: 2508

The "\" character in Python is a string escape, and it introduces shortcuts for certain string characters. For example the string "\n" doesn't contain the characters \ and n. It contains a newline character. Windows paths always cause this trouble in Python. When Python sees "\U", it's looking for some unicode escape that doesn't exist.

You can use raw strings in Python by prepending the string with r.

searchFolder = r"C:\Users\rohrl\OneDrive\Python\PictureCompare\MixedPictures"

Or you can get in the habit of using double \\. Python reads \\ as a single \.

searchFolder = "C:\\Users\\rohrl\\OneDrive\\Python\\PictureCompare\\MixedPictures"

Upvotes: 2

Related Questions