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:
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