首页 > 解决方案 > 在文件夹中查找下一个文件

问题描述

我在文件夹中获取下一个文件的名称的方法很糟糕,但很有效。我想删除调用 os.listdir 函数的要求,因为它在大文件夹中很慢,但不知道如何。欢迎任何帮助。

注意:fullpathtoimagefile 是旧文件 changeimage 是获取下一个文件的函数的名称

def nextfile(self):
    folder, filename = os.path.split(fullpathtoimagefile)
    filelist = os.listdir(folder)
    nextfile = filelist.index(filename) + 1
    nextfilename = filelist[nextfile]
    changeimage(os.path.join(folder, nextfilename))

tl;dr 获取文件夹中下一个文件全名的更有效方法

标签: pythonperformancefiledirectoryos.path

解决方案


简单的代码..

import os

arq = (os.listdir(".")) # "." = directory name
for file in arq:
    print(file)

另一个例子:

import os

arq = (os.listdir("."))
for file in arq:
    if (os.path.splitext(file)[1] == ".jpg"): #if a JPG file, do something
        print(file)

推荐阅读