Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Try and except with os.chdir

I work from two different computers with the same script. Writing files to my cloud storage \has a slightly different path on both computers. I thought I could use a try-except to simply see which path works (depending on which computer I am using).

I thought I could solve this by doing the following:

import os
try:
    os.chdir('C://Users//comp1//Cloud//Data')
except:
    os.chdir('C://Users//comp2//Cloud//Data')

However if I run it, I still get:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C://Users//comp1//Cloud//Data')

Could someone tell me what I am doing wrong here, or whether I should perhaps use a different solution.

>Solution :

As multiple comments have suggested, replace the double forward slashes with one forward slash, or use double backward slashes.

Now I ran your code and it does seem to work, but it depends on the context (is this your entire script?). However you could do better with a if-else statement rather than try-except because the latter is a lot slower first of all, and generally not the best practice.

import os

if os.path.isdir('C:/Users/comp1/Cloud/Data'):
    os.chdir('C:/Users/comp1/Cloud/Data')
elif os.path.isdir('C:/Users/comp2/Cloud/Data'):
    os.chdir('C:/Users/comp2/Cloud/Data')

If you’d like to stick to try-except and neither directories exist, you could try using nesting your try-except like this:

Edit: Forgot to mention, thanks @Tzane, do not use bare try-except statements.

import os

try:
    try:
        os.chdir('C:/Users/comp1/Cloud/Data')
    except FileNotFoundError:
        os.chdir('C:/Users/comp2/Cloud/Data')
except FileNotFoundError:
    # handle the case where neither directory exist
    pass

Or to combine the two suggestions:

import os

if os.path.isdir('C:/Users/comp1/Cloud/Data'):
    os.chdir('C:/Users/comp1/Cloud/Data')
elif os.path.isdir('C:/Users/comp2/Cloud/Data'):
    os.chdir('C:/Users/comp2/Cloud/Data')
else:
    # handle the case where neither directory exist
    pass
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading