Search code examples
python-3.8

Python os path join ignores folder names


I am doing the following:

import os
ii = r'Z:\Monthly\iOT\2021'
dir0 = os.path.splitdrive(ii)[1]
dir1 = os.path.join(r'G:', r'My Drive', dir0)

print(dir1) gives 'G:\\Monthly\\iOT\\2021' and completely ignores 'My Drive'. I understand it has something to do with two backslashes in front of dir0 but not sure how to remove it.

I was expecting

'G:\\My Drive\\Monthly\\iOT\\2021'

Solution

  • You can do as following

    os.path.join('G:\\', r'My Drive', dir0[1:])
    

    This "slices" the result of dir0, getting the characters from index 1 to the end of the string

    This will result in

    'G:\\My Drive\\Monthly\\iOT\\2021'
    

    Remember the following, as stated in the docs

    On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.