1

i want to confirm if i am present in C:/Users/Dell/Desktop/Python folder and then only create a folder there.

I am using below code:


import os
pwd=os.getcwd()
myDir="C:/Users/Dell/Desktop/Python"
print(pwd)
print(myDir)
if pwd==myDir:
    direx=os.path.isdir("xyz")
    if direx==False:
        os.makedirs("xyz")
        direx=os.path.isdir("xyz")
        if direx==True:
            print("directory xyz is created")

I am getting below output:

C:\Users\Dell\Desktop\Python
C:/Users/Dell/Desktop/Python

if i assign C:\Users\Dell\Desktop\Python to myDir i am getting below error:

(unicode error) 'unicodeescape' codec cant decode bytes in position 2-3:truncated \UXXXXXXXXXX escape

can somebody help

  • 1
    `myDir=r"C:\Users\Dell\Desktop\Python"` – Bibhav Aug 20 '23 at 08:27
  • 1
    Does this answer your question? [How should I write a Windows path in a Python string literal?](https://stackoverflow.com/questions/2953834/how-should-i-write-a-windows-path-in-a-python-string-literal) – slothrop Aug 20 '23 at 09:02

1 Answers1

0

Hello i hope you are doing well. The error because of the backslashes in the file path being interpreted as escape characters. So you could use a raw string instead of ordinary string

here how you can update your code .

import os

pwd = os.getcwd()
myDir = r"C:\Users\Dell\Desktop\Python"  # Use a raw string insteaf of string

print(pwd)
print(myDir)

if pwd == myDir:
    direx = os.path.isdir("xyz")
    if not direx:
        os.makedirs("xyz")
        direx = os.path.isdir("xyz")
        if direx:
            print("directory xyz is created")

I hope this helps.