How can I change drives using python os?
Asked Answered
C

3

9

I'm trying to change the current directory from C: to Y: I tried:

import os
os.chdir('Y:')

but I keep getting an error saying that it can't locate the drive. Essentially I'm looking for the equivalent of the

cd /d

command in cmd.

Counterglow answered 15/6, 2012 at 19:47 Comment(2)
You realize that "change the current directory from C: to Y:" doesn't actually mean anything in Windows? There's a current default drive, and a separate current directory for each drive. So, you can change the current drive to Y:, or you can change the current drive to Y: and change the directory on that to \, but those are different operations. (At the C API level it's _chdrive(25) vs. _chdir("Y:\\"), and it's probably similar in Python, except that chdrive probably doesn't exist in os and you have to go to msvcrt, or even ctypes the actual MSVCRT DLL.)Sublease
I realized my connection to Y: had been disrupted somehow, but once I sorted that out chdir('Y:') worked fine. Thanks for the help in any case.Counterglow
L
12

Are you sure Y: really is a valid drive letter?

Try os.chdir('C:') and make sure that works. (It works for me.)

Linhliniment answered 15/6, 2012 at 19:50 Comment(3)
I have a Y: drive and I have been able to access it using "cd /d Y:"Counterglow
@aensm: Even if os.chdir('Y:') worked, it doesn't do the same thing as a "cd /d Y:" does. See @abarnert's comment.Delly
my guess is that Y: in not a drive, while Y:\ is.Sturm
W
3

If this is a mapped network drive, your best bet is to use the UNC path instead of the mapped path. Also, try to use a raw r string modifier when using paths under windows, if you're not using os.path.join.

import os
print os.getcwd()
os.chdir(r'\\server\path') 
print os.getcwd()
Woodsum answered 15/6, 2012 at 20:15 Comment(0)
S
-1

If you are doing (Drive:path\to\folder) try switching the slashes to (Drive:path/to/folder)

Smolder answered 19/11, 2020 at 6:25 Comment(1)
This does not answer the question. The OP is asking to change drives not folders.Carcinogen

© 2022 - 2024 — McMap. All rights reserved.