在Python中缩减路径名

2024-09-30 01:30:30 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我当前的代码:

directory = "C:/Users/test/Desktop/test/sign off img"
choices = glob.glob(os.path.join(directory, "*.jpg"))
print(choices)

这将返回到该特定文件夹中所有.JPG文件的每个路径。你知道吗

例如,以下是当前上述代码的输出:

['C:/Users/test/Desktop/test/sign off img\\SFDG001 0102400OL - signed.jpg', 'C:/Users/test/Desktop/test/sign off img\\SFDG001 0102400OL.jpg']

如何使输出只返回路径的结尾?你知道吗

这是我渴望的结果:

['SFDG001 0102400OL - signed.jpg', 'SFDG001 0102400OL.jpg']

相同的路径,但只返回结束字符串。你知道吗


Tags: 代码test路径imgosusersdirectoryglob
2条回答

可以使用^{}函数:

>>> import os
>>> files = os.listdir("C:/Users/test/Desktop/test/sign off img")
>>> filtered_files = [file for file in files if 'signed' in file]

正如您在电子文档中看到的,os.listdir使用当前目录作为默认参数,即,如果您不传递值。否则,它将使用您传递给它的路径。你知道吗

我建议大部分时间都使用pathlib.Path而不是os。试试这个,例如:

from pathlib import Path

directory = Path("C:/Users/test/Desktop/test/sign off img")
choices = [path.name for path in directory.glob("*.jpg")]

相关问题 更多 >

    热门问题