Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python os.path.join on Windows

I am trying to learn python and am making a program that will output a script. I want to use os.path.join, but am pretty confused. According to the docs if I say:

os.path.join('c:', 'sourcedir') 

I get "C:sourcedir". According to the docs, this is normal, right?

But when I use the copytree command, Python will output it the desired way, for example:

import shutil src = os.path.join('c:', 'src') dst = os.path.join('c:', 'dst') shutil.copytree(src, dst) 

Here is the error code I get:

 WindowsError: [Error 3] The system cannot find the path specified: 'C:src/*.*' 

If I wrap the os.path.join with os.path.normpath I get the same error.

If this os.path.join can't be used this way, then I am confused as to its purpose.

According to the pages suggested by Stack Overflow, slashes should not be used in join—that is correct, I assume?

like image 427
Frank E. Avatar asked Mar 11 '10 05:03

Frank E.


People also ask

How does os path join work in Windows?

path. join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator ('/') following each non-empty part except the last path component.

What is os path join?

os. path. join combines path names into one complete path. This means that you can merge multiple parts of a path into one, instead of hard-coding every path name manually.


1 Answers

To be even more pedantic, the most python doc consistent answer would be:

mypath = os.path.join('c:', os.sep, 'sourcedir') 

Since you also need os.sep for the posix root path:

mypath = os.path.join(os.sep, 'usr', 'lib') 
like image 183
AndreasT Avatar answered Oct 06 '22 06:10

AndreasT