我会使用python的模块os:
我的文件在目录中:/Users/ach/Documents/Data_Science/img/
版本 1:
优雅版:
import os
DIR_WITH_FILES='/Users/ach/Documents/Data_Science/img'
list_png=[f for f in sorted(os.listdir(DIR_WITH_FILES)) if (str(f))[-3:] == "png"]
list_png_with_path=[DIR_WITH_FILES+'/'+str(f) for f in list_png]
版本 2:
一步一步:
code_1:导入os并给出文件所在目录的路径
import os
print(os.getcwd())
MY_WORKING_DIRECTORY=os.getcwd()
!ls
DIR_WITH_FILES=MY_WORKING_DIRECTORY+'/img/'
print(DIR_WITH_FILES)
输出_1:
Users/ach/Documents/Data_Science
img notebooks
/Users/ach/Documents/Data_Science/img/
code_2:列出目录DIR_WITH_FILES=/Users/ach/Documents/Data_Science/img的文件
files=sorted(os.listdir(DIR_WITH_FILES))
print(files)
输出_2:
['fig_0.png', 'fig_describe_target_0.png', 'fig_describe_target_1.png', 'test.txt']
code_3:创建两个带有扩展名的文件名的列表 png => list_png,以及另一个带有文件名的列表及其路径 => list_png_with_path :
list_png=[]
list_png_with_path=[]
for f in sorted(os.listdir(DIR_WITH_FILES)):
if (str(f))[-3:] == "png":
list_png.append(f)
png_with_path=DIR_WITH_FILES+str(f)
list_png_with_path.append(png_with_path)
print(list_png)
print(list_png_with_path)
输出_3:
['fig_0.png', 'fig_describe_target_0.png', 'fig_describe_target_1.png']
['/Users/ach/Documents/Data_Science/img/fig_0.png', '/Users/ach/Documents/Data_Science/img/fig_describe_target_0.png', '/Users/ach/Documents/Data_Science/img/fig_describe_target_1.png']
您可以看到文件'test.txt' 未包含在列表中。
如果您想过滤多个扩展程序,只需遍历 code_3
您也可以查看:Get a filtered list of files in a directory