Solve the problem that Python reads the image path with escape characters

A general solution to the problem of escape characters in paths

The general solution to the problem of escape characters is nothing more than the following three.

1. Add r before the path

Add r directly in front of the path, this method can keep the original meaning of the characters.

For example, the following:

path=r"D:\MindSpore\Dearui\source\ces\0AI.png"

2. Replace the backslash "\" with a forward slash

path="D:\MindSpore\Dearui\source\ces/0AI.png"

3. Replace the backslash "\" with a double backslash "\\"

path="D:\\MindSpore\\Dearui\\source\\ces\\0AI.png"

Use os to read the path of the image

Here we use os to connect folder names and file names.

The specific method is as follows:

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)

Finally, we first print out this list directly.

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

When using os here, you can see that double backslashes are automatically used, which effectively avoids escape characters, but there is a problem involving the list reading mechanism.

for f in imgfile:
    print(f)

Generally, we use the for loop to obtain the image path in the list, but here it is not as I thought.

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

Using the for loop to read, the double backslashes have been changed into single slashes, which leads to escape characters in the read path, which may involve the problem of the reading mechanism. The specifics are not mentioned here. After exploring, let's talk about the solution below.

The approach taken in this article

Simply through the os, the path we get is double backslashes. After all, even '\' is an escape character, and we really have no way to change it.

newph = os.path.join(paths, i).replace("\\","/")

This modification can complete the modification of the escape character, and the value printed through the for loop is also eligible.

The for loop prints:

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

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

This function is also included in pyzjr by me, and it can only be seen after downloading version 0.0.19.

pip install pyzjr==0.0.19
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

Here I added a hint, which can point out which file may be wrong, so as to facilitate the search for subsequent problems. The one that can be modified manually is actually the last, but if you insist on using it, there is no problem.

correct:

At present, this function has been improved, and pip install pyzjr==1.0.5 and higher versions can be downloaded:

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

No further corrections are expected in the future.

Guess you like

Origin blog.csdn.net/m0_62919535/article/details/132199978