Unicode Chars in Windows Path

alister alister.nospam.ware at ntlworld.com
Thu Apr 3 04:35:38 EDT 2014


On Wed, 02 Apr 2014 16:27:04 -0700, Steve wrote:

> Hi All,
> 
> I'm in need of some encoding/decoding help for a situation for a Windows
> Path that contains Unicode characters in it.
> 
> ---- CODE ----
> 
> import os.path import codecs import sys
> 
> All_Tests =
> [u"c:\automation_common\Python\TestCases\list_dir_script.txt"]
> 
> 
> for curr_test in All_Tests:
>   print("\n raw : " + repr(curr_test) + "\n")
>   print("\n encode : %s \n\n" ) % 
>   os.path.normpath(codecs.encode(curr_test, "ascii"))
>   print("\n decode : %s \n\n" ) %  curr_test.decode('string_escape')
> 
> ---- CODE ----
> 
> 
> Screen Output :
> 
>  raw : u'c:\x07utomation_common\\Python\\TestCases\\list_dir_script.txt'
> 
>  encode : c:utomation_common\Python\TestCases\list_dir_script.txt
> 
>  decode : c:utomation_common\Python\TestCases\list_dir_script.txt
> 
> 
> My goal is to have the properly formatting path in the output :
> 
> 
> c:\automation_common\Python\TestCases\list_dir_script.txt
> 
> 
> What is the "magic" encode/decode sequence here??
> 
> Thanks!
> 
> Steve

you have imported os.path you will find it contains a number of functions 
to make this task easier*

import os.path
root=os.path.sep
drive='c:'
path= [root,
	'automation_common','python',
	'TestCases','list_dir_script.txt']
all_tests=os.path.join(drive,*path)

works happily even in linux (the un-necessary drive letter simply gets 
stripped)

*easier to maintain cross platform compatibility



More information about the Python-list mailing list