Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two windows paths, one containing tilde, in python

I'm trying to use the TMP environment variable in a program. When I ask for

tmp = os.path.expandvars("$TMP")

I get

C:\Users\STEVE~1.COO\AppData\Local\Temp

Which contains the old-school, tilde form. A function I have no control over returns paths like

C:\Users\steve.cooper\AppData\Local\Temp\file.txt

My problem is this; I'd like to check if the file is in my temp drive, but I can't find a way to compare them. How do you tell if these two Windows directories;

C:\Users\STEVE~1.COO\AppData\Local\Temp
C:\Users\steve.cooper\AppData\Local\Temp

are the same?

like image 492
Steve Cooper Avatar asked Apr 29 '10 15:04

Steve Cooper


People also ask

How do you compare two paths in Python?

path. samefile() method in Python is used to check whether the given two pathnames refer to the same file or directory or not. This is determined by comparing device number and i-node number of the given paths.

Can you use tilde in path?

Thus tilde slash (~/) is the beginning of a path to a file or directory below the user's home directory. For example, for user01, file /home/user01/test. file can also be denoted by ~/test.

What does tilde mean in Windows path?

From Wikipedia: “The tilde symbol is used to prefix hidden temporary files that are created when a document is opened in Windows. For example, when you open a Word document called “Document1. doc,” a file called “~$cument1. doc” is created in the same directory.

How do you find the relative path in Python?

A relative path starts with / , ./ or ../ . To get a relative path in Python you first have to find the location of the working directory where the script or module is stored. Then from that location, you get the relative path to the file want.


1 Answers

Here is alternative solution using only ctypes from Standard Python Library.

tmp = unicode(os.path.expandvars("$TMP"))

import ctypes
GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
buffer = ctypes.create_unicode_buffer(GetLongPathName(tmp, 0, 0))
GetLongPathName(tmp, buffer, len(buffer))
print buffer.value
like image 192
Constantin Avatar answered Sep 23 '22 04:09

Constantin