python - 在 Python 中减少路径名

标签 python glob

这是我当前的代码:

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

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

最佳答案

您可以使用 os.listdir功能:

>>> 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 使用当前目录作为默认参数,即如果您不传递值。否则,它将使用您传递给它的路径。

关于python - 在 Python 中减少路径名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57981447/

相关文章:

python - 如何使用python根据数据框中的列元素更改文件夹中的文件名

ruby - 如何测试字符串是否与 Ruby 中的 glob 匹配?

python - 设置 Pandas 索引开始和结束的优雅方法是什么

python - 如何*实际上*从 numpy 结构化数组中删除一列(以便它不会显示在二进制文件中)

Ruby:从目录中获取前几个文件?

package - pipenv 安装 glob 失败

python - 使 glob 目录变量

python - 如何使用python杀死资源消耗不变的Windows进程?

python - Multiprocessing.pool 错误 : raise self. _value sre_constants.error: 不平衡的括号

python - 如何为python中dict对象的所有键设置默认值?