1

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.

Community
  • 1
  • 1
Bryce Thomas
  • 10,479
  • 26
  • 77
  • 126

2 Answers2

3

"\\\\?\\" 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 ;-))

Jürgen A. Erhard
  • 4,908
  • 2
  • 23
  • 25
  • Raw string literals are to escape escape-sequences (`\"`, `\n`, `\(`, `\s`, etc.), which is why you can't end one in a backslash. –  Dec 26 '09 at 14:30
  • Yep, this works. I'd tried this before and gotten an error, although that turned out to be because I had been doing it with a file path like "\\?\D:somefile" instead of "\\?\D:\somefile". – Bryce Thomas Dec 26 '09 at 16:49
0

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.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251