解决Python读取图片路径存在转义字符

普遍解决路径中存在转义字符的问题的方法

普遍解决转义字符的问题,无非是以下这三种。

一、在路径前添加r

直接在路径前面加r,这种方法能够使字符保持原始的意思。

比如下面这种:

python 复制代码
path=r"D:\MindSpore\Dearui\source\ces\0AI.png"

二、将反斜杠"\"替换为正斜杠

python 复制代码
path="D:\MindSpore\Dearui\source\ces/0AI.png"

三、将反斜杠"\"替换为双反斜杠"\\"

python 复制代码
path="D:\\MindSpore\\Dearui\\source\\ces\\0AI.png"

使用os来读取图片的路径

这里我们采用了os来连接文件夹名与文件名。

具体方法如下:

python 复制代码
paths=r"D:\MindSpore\Dearui\source\ces"
imgfile = []
file_list = os.listdir(paths)
for i in file_list:
    newph = os.path.join(paths, i)
    imgfile.append(newph)
print(imgfile)

最后我们先直接打印出这个列表。

'D:\\\\MindSpore\\\\Dearui\\\\source\\\\ces\\\\0AI.png', 'D:\\\\MindSpore\\\\Dearui\\\\source\\\\ces\\\\AI2.png', 'D:\\\\MindSpore\\\\Dearui\\\\source\\\\ces\\\\AI3.png'

这里在用os时,可以看见是自动采用的是双反斜杠,有效规避了转义字符,但这里有涉及到了列表读取机制的问题。

python 复制代码
for f in imgfile:
    print(f)

一般我们是通过for循环这种方式来获取列表中的图片路径,然而这里却并非如我所想。

D:\MindSpore\Dearui\source\ces\0AI.png

D:\MindSpore\Dearui\source\ces\AI2.png

D:\MindSpore\Dearui\source\ces\AI3.png

使用for循环读取,竟然将双反斜杠变为了单斜杠,这也就导致了读取路径中存在了转义字符,这里面可能涉及到读取机制的问题,具体是什么这里就不探究了,下面我们来说下解决方案。

本文采取的方法

索性的是通过os,我们获得的路径是双反斜杠,毕竟连'\'这种都属于是转义字符,我们还真没什么办法对它进行变化。

python 复制代码
newph = os.path.join(paths, i).replace("\\","/")

这样修改就可以完成对转义字符的修改,并且通过for循环打印出来的值也是符合条件的。

for循环打印:

D:/MindSpore/Dearui/source/ces/0AI.png

D:/MindSpore/Dearui/source/ces/AI2.png

D:/MindSpore/Dearui/source/ces/AI3.png

列表打印:

'D:/MindSpore/Dearui/source/ces/0AI.png', 'D:/MindSpore/Dearui/source/ces/AI2.png', 'D:/MindSpore/Dearui/source/ces/AI3.png'

此函数也被我收录进了pyzjr中,需要下载0.0.19版本之后才可见。

python 复制代码
pip install pyzjr==0.0.19
python 复制代码
def getPhotopath(paths):
    """
    * log:0.0.19以后修改了一个比较大的bug,使用os读取的路径是"\\",本来是没有问题的,
    但如果使用列表循环读取,居然变成了单斜杠。
    * 功能:批量读取文件夹下的图片路径
    :param paths: 文件夹路径
    :return: 包含图片路径的列表
    """
    imgfile = []
    file_list = os.listdir(paths)
    for i in file_list:
        if i[0] in ['n', 't', 'r', 'b', 'f'] or i[0].isdigit():
            print(f"Error: 文件名 {i} 开头出现错误!")
        newph = os.path.join(paths, i).replace("\\","/")
        imgfile.append(newph)
    return imgfile

这里我添加了提示,可以指出可能是哪个文件出错了,便于后续问题的查找,能够手动修改的,其实是最后的,但如果你执意要用也是没有任何问题的。

更正:

目前此函数已经重新完善,可下载pip install pyzjr==1.0.5及更高的版本:

python 复制代码
def getPhotopath(paths,cd=False,debug=True):
    """
    * log
        0.0.19以后修改了一个比较大的bug
        1.0.2后将图片和所有文件路径分开
        1.0.5功能全部完善,不会再进行更新
    :param paths: 文件夹路径
    :param cd:添加当前运行的路径名
    :param debug:开启打印文件名错误的名字
    :return: 包含图片路径的列表
    """
    img_formats = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tif', 'tiff', 'webp', 'raw']
    imgfile = []
    allfile = []
    file_list = os.listdir(paths)
    for i in file_list:
        if debug:
            if i[0] in ['n', 't', 'r', 'b', 'f'] or i[0].isdigit():
                print(f"Error: 文件名 {i} 开头出现错误!")
        newph = os.path.join(paths, i).replace("\\", "/")
        allfile.append(newph)
        _, file_ext = os.path.splitext(newph)
        if file_ext[1:] in img_formats:
            imgfile.append(newph)
    if cd:
        cdd = getcwd()
        imgfile = [os.path.join(cdd, file).replace("\\", "/") for file in imgfile]
        allfile = [os.path.join(cdd, file).replace("\\", "/") for file in allfile]
    return imgfile,allfile

预计以后也不会再进行更正了。

相关推荐
北京耐用通信28 分钟前
电磁阀通讯频频“掉链”?耐达讯自动化Ethernet/IP转DeviceNet救场全行业!
人工智能·物联网·网络协议·安全·自动化·信息与通信
cooldream200933 分钟前
小智 AI 智能音箱深度体验全解析:人设、音色、记忆与多场景玩法的全面指南
人工智能·嵌入式硬件·智能音箱
oil欧哟35 分钟前
AI 虚拟试穿实战,如何低成本生成模特上身图
人工智能·ai作画
NiNi_suanfa1 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
小糖学代码1 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
央链知播1 小时前
中国移联元宇宙与人工智能产业委联席秘书长叶毓睿受邀到北京联合大学做大模型智能体现状与趋势专题报告
人工智能·科技·业界资讯
人工智能培训1 小时前
卷积神经网络(CNN)详细介绍及其原理详解(2)
人工智能·神经网络·cnn
Data_agent1 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
YIN_尹2 小时前
目标检测模型量化加速在 openEuler 上的实现
人工智能·目标检测·计算机视觉
妖灵翎幺2 小时前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide