反斜杠后如何用数字管理路径? [英] How to manage a path with numbers after backslashes?

查看:72
本文介绍了反斜杠后如何用数字管理路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Windows 7上使用Python 3.3.

I am using Python 3.3 on Windows 7.

这是问题所在.

当我使用以数字开头的文件名时,它更改为错误.

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

例如:

>>> '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'

或在字符串前面添加"r".

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?

更新: 正如@Blender建议的那样,我将发布代码.当我重写它时,我意识到原来是有一个错误,导致我得出错误的结论.据我了解,上述情况在需要动态生成带有原始路径的字符串时不会发生.只有在手动编写路径时才能发生这种情况.

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?

推荐答案

\仅在字符串文字中使用时才重要.

\ only matters when it is used in string literal.

>>> path = input() # `a\n\1` in the following line is typed by me (user).
a\n\1
>>> path
'a\\n\\1'

这篇关于反斜杠后如何用数字管理路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆