Yet another interesting ‘fact’ with literal paths and python
Oh boy I’m getting good with these things… The following is an example of an interesting behavior you will find with python if you use \?
path = 'C:\Users\Mandel\COM1' with open(path, 'w') as fd: fd.write('hello') [Errno 2] Not such file or directory 'C:\Users\Mandel\COM1'
Lets try with a .txt for testing.
path = 'C:\Users\Mandel\COM1.txt' with open(path, 'w') as fd: fd.write('hello') [Errno 2] Not such file or directory. 'C:\Users\Mandel\COM1.txt'
Ok, lets bring our awesome friend \? in the game:
path = '\\?\C:\Users\Mandel\COM1' with open(path, 'w') as fd: fd.write('hello')
Works o/. You may wonder what is going on here… Well, \? allows you to use COM1, yet this approach has a very interesting result:
os.chdir('c:\Users\Mandel') for file in os.listdir('.'): print os.path.abspath(file) C:Usersmandeltest.py C:Usersmandelnotes.txt \.COM1
WTF is the least I can say. It turns out that os.path.abspath considers that the abspath of the COM1 file present in the hd is the COM7 device.. cute!. What is even more, if you create a file COM1 and a COM1.txt you will get \.COM1 for both files. As soon as I have some time away from Mac OS X I’ll propose a fix for this in Ubuntu One. Sometime I really wonder if I will ever use this knowledge in any other application.