【发布时间】:2023-03-05 17:00:01
【问题描述】:
我在 Windows 7 上使用 Python 3.3。
这就是问题所在。
当我的文件名以数字开头时,它会更改错误。
例如:
>>> 'E:\DOCUMENTS\1.jpg'
'E:\\DOCUMENTS\x01.jpg'
我知道我可以通过添加转义反斜杠来手动修复它。
>>> 'E:\DOCUMENTS\\1.jpg'
'E:\\DOCUMENTS\\1.jpg'
或者在字符串前面加上“r”。
>>> r'E:\DOCUMENTS\1.jpg'
'E:\\DOCUMENTS\\1.jpg'
但我不能手动完成,因为我不知道路径是什么。
有哪些可能的解决方案?
更新: 正如@Blender 建议的那样,我打算发布代码。当我重写它时,我意识到原来有一个错误,导致我得出错误的结论。据我了解,上述情况,当需要动态生成具有原始路径的字符串时不会发生。只有手动编写路径时才会发生。
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)
所以现在我只是想确认一下,当需要动态生成一个带有原始路径的字符串时,这个问题永远不会真正发生,是吗?
【问题讨论】:
-
这不是“修复”:这实际上是字符串的表示方式。
\1是\x01。只是出于好奇,这个问题是怎么出现的?为什么事先不知道路径是什么很重要? -
我想用 PIL 模块打开图片,那些名字以数字开头的文件,我打不开。
-
这没有意义。你是怎么得到这些名字的?
-
我使用 os.listdir 和 os.path.abspath。
-
如果有类似 'E:\DOCUMENTS\1.jpg' 的内容,我会收到这样的错误。文件“C:\Python33\lib\site-packages\PIL\Image.py”,第 1974 行,打开 OSError:[Errno 22] 无效参数:'E:\\DOCUMENTS\x01.jpg'
标签: python python-3.x path