How to manage a path with numbers after backslashes?

Viewed 611

I am using Python 3.3 on Windows 7.

Here is the problem.

When I have a filename starting with a number it changes wrong.

For example:

>>> 'E:\DOCUMENTS\1.jpg'
'E:\\DOCUMENTS\x01.jpg'

I am aware that I can fix it manually by adding an escaping backslash.

>>> 'E:\DOCUMENTS\\1.jpg'
'E:\\DOCUMENTS\\1.jpg'

Or by adding "r" in front of the string.

>>> r'E:\DOCUMENTS\1.jpg'
'E:\\DOCUMENTS\\1.jpg'

But I cannot do it manually, because I don't know what the path will be.

What are the possible solutions?

UPDATE: As @Blender suggested, I was going to post the code. When I rewrote it, I realized that originally there was a mistake, that leaded me to a wrong conclusion. As far as I have understood, the described above situation, when it is necessary to make a string with a path raw dynamically does not happen. It can only happen when the path is written manually.

import os
from PIL import Image as PIL
from PIL import ImageTk

def searchforimages(dir):
    imagelist=[]
    for file in os.listdir(dir):
        fileabspath=os.path.join(dir,file)
        try:
            # the problem was here originally, but now it is ok.
            # since "fileabspath" get passes as a raw string,
            # so there is no problem for PIL.open() to open it
            PIL.open(fileabspath)
            imagelist.append(fileabspath)
        except:
            continue
    return imagelist

searchforimages('E:\photos')

#the problem only happens, when path is written manually
path='E:\photos\1.jpg'
PIL.open(path)

So now I just want to confirm, the problem when it is necessary to make a string with a path raw dynamically never really happens, does it?

1 Answers
Related