Question

I'm trying to work with some long file paths (Windows) in Python and have come across some problems. After reading the question here, it looks as though I need to append '\\?\' to the front of my long file paths in order to use them with os.stat(filepath). The problem I'm having is that I can't create a string in Python that ends in a backslash. The question here points out that you can't even end strings in Python with a single '\' character.

Is there anything in any of the Python standard libraries or anywhere else that lets you simply append '\\?\' to the front of a file path you already have? Or is there any other work around for working with long file paths in Windows with Python? It seems like such a simple thing to do, but I can't figure it out for the life of me.

Was it helpful?

Solution

"\\\\?\\" should give you exactly the string you want.

Longer answer: of course you can end a string in Python with a backslash. You just can't do so when it's a "raw" string (one prefixed with an 'r'). Which you usually use for strings that contains (lots of) backslashes (to avoid the infamous "leaning toothpick" syndrome ;-))

OTHER TIPS

Even with a raw string, you can end in a backslash with:

>>> print r'\\?\D:\Blah' + '\\'
\\?\D:\Blah\

or even:

>>> print r'\\?\D:\Blah' '\\'
\\?\D:\Blah\

since Python concatenates to literal strings into one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top