Search code examples
pythonpathcd

Error when using python to change directories in script


I am creating a program that will convert files. My main issue is that I need my program to change the working directory. I have the code for that, but it keeps saying that there is:

OSError: [Errno 2] No such file or directory:

Do you guys have any ideas.

Here is my current code:

if filetype == "Document":
    path = raw_input("Please enter the path to the folder your file is stored in. An example path is /home/Documents/: ")
    os.chdir(path)
    filename = raw_input("Please enter the name of the file you would like to convert, including the filetype. e.g. test.txt:")


elif filetype == "Audio":
    path = raw_input("Please enter the path to the folder your file is stored in. An example path is /home/Music/: ")
    os.chdir(path)
    filename = raw_input("Please enter the name of the file you would like to convert, including the filetype. e.g. test.txt:")


elif filetype == "Video":
    path = raw_input("Please enter the path to the folder your file is stored in. An example path is /home/Movies/: ")
    os.chdir(path)
    filename = raw_input("Please enter the name of the file you would like to convert, including the filetype. e.g. test.txt:")


elif filetype == "Image":
    path = raw_input("Please enter the path to the folder your file is stored in. An example path is /home/Pictures/: ")
    os.chdir(path)
    filename = raw_input("Please enter the name of the file you would like to convert, including the filetype. e.g. test.txt:")

When I input as a path:

/home/Pictures/

I get the error:

Traceback (most recent call last):
  File "conversion.py", line 29, in <module>
    os.chdir(path)
OSError: [Errno 2] No such file or directory: '/home/Pictures/'

I have checked and this does indeed work when I write this as cd /home/Pictures/ it works.


Solution

  • Why not skip the extra step and ask for the files path directly? You could derive the directory from that if needed... but perharps it won't be needed.

    When I've done stuff like this I've suggested that the user simply drag the file or folder to the commandline because it's easy to make a simple input error in the path and not catch it.