os.path.join doubt

Nobody nobody at nowhere.com
Thu Feb 3 10:59:28 CET 2011


On Thu, 03 Feb 2011 06:31:49 +0000, Steven D'Aprano wrote:

> On Wed, 02 Feb 2011 20:46:12 -0800, harryos wrote:
> 
>> In windows ,I tried this
>> 
>> p1 = "C:\Users\me\Documents"
>> p2 = "..\Pictures\images\my.jpg"

Don't do this; backslash is significant within Python string literals. If
want to use literal backslashes in a string literal, either double them:

	p1 = "C:\\Users\\me\\Documents"

or use a raw literal:

	p1 = r"C:\Users\me\Documents"

You got away with it because backslash is only significant when followed
by specific characters, none of which occurred in this case.

> BTW, Windows accepts / as well as \ as a path separator. You will have 
> far fewer headaches if you use that.

Unless you need to pass strings to the command interpreter, which has its
own interpretation of forward slashes. Apart from that, while forward
slashes are supported by Windows itself, they aren't the "standard"
separator, and may not be supported by other programs running on Windows.

In general, directory separators shouldn't occur within string
literals. Base directories should be taken from command-line parameters,
registry entries, configuration files, environment variables etc, not
embedded into the program. Paths relative to those directories should be
constructed with os.path.join().




More information about the Python-list mailing list