Search code examples
pythonwindowspython-os

os.chdir(src_path) error while accepting User Input using directory path in Python 3.9


Code Snippet:

src_path = input("enter the src direc : " )
print("src path ",src_path)
dst_path = input("enter the dest direc: " )

os.chdir(src_path) # It errors at this line

Getting this error after accepting the user input directory.

enter the src direc : "C:\Src_html"  # (<< This is what i entered as the path, also tried giving "C\\ ' same error
src path  "C:\Src_html"
enter the dest direc: "C:\Src_html"
dest path  "C:\Src_html"

When the code gets here , it throws an error as shown below

os.chdir(src_path)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '"C:\\Src_html"'

Solution

  • The problem is that the user input isn’t valid:

    enter the src direc : "C:\Src_html"
    

    The user entered "C:\Src_html" instead of C:\Src_html. So that src_path save a path with a " at the start and the end, and as an str object (because input return str) it wraps the path again with another '. So that src_path looking like this: '"C:\Src_html"', Double ".

    And you can see on the massage, that this is the path it is holding:

    OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '"C:\\Src_html"'