0

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.

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the great explanation. As I'm beginning to learn python this is very useful!
1

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())

1 Comment

Thank you for pointing out the various ways of doing it. I might take one of those routes in the future!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.