You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断os.listdir()遍历目录时当前处理的文件是否为最后一个

实现方案

核心逻辑是先把os.listdir()返回的文件名列表提前存储,再通过遍历索引判断当前文件是否为最后一个,同时还补充了路径安全、异常兼容的优化:

优化后完整代码

import os
import csv
import datetime

# 提前获取所有目标文件:过滤非文件、可指定排序规则保证遍历顺序稳定
file_list = sorted([
    f for f in os.listdir(edgar_path) 
    if os.path.isfile(os.path.join(edgar_path, f))
])
total_files = len(file_list)

# iterate through all files in directory
for idx, filename in enumerate(file_list):
    # 判断是否为最后一个文件
    is_last_file = (idx == total_files - 1)
    # 路径拼接用os.path.join避免不同系统的分隔符问题
    file_path = os.path.join(edgar_path, filename)
    # open and read
    with open(file_path, 'r') as file:
        # rearrange by date (column 3)
        tsv_file = sorted(list(csv.reader(file, delimiter='|')), key=lambda t: t[3])

        # get date today
        today = datetime.datetime.now()  
        # get start date and end date depending on the first and last row
        start_date = datetime.datetime.strptime(tsv_file[0][3], "%Y-%m-%d")
        end_date = datetime.datetime.strptime(tsv_file[-1][3], "%Y-%m-%d")
        # check print
        logger.debug(start_date)
        logger.debug(end_date)
        # if within date range
        if start_date <= today <= end_date:
            logger.debug('pass condition 1')
        # if not within date range, but
        # the date today is greater than the end date 
        # and its the last file being checked so it still passes
        elif today >= end_date and is_last_file:
            logger.debug('pass condition 2')
        # add to delete files if both conditions are unmet
        else:
            files_to_delete.append(filename)
            logger.debug('no pass')

补充说明

  • 我们对文件名列表做了排序,避免不同操作系统下os.listdir()返回顺序不一致,导致最后一个文件的判断结果不稳定,如果不需要固定排序可以去掉外层的sorted()
  • 新增了os.path.isfile()过滤逻辑,自动跳过目录、符号链接等非文件对象,避免后续open操作报错
  • 原代码里取列表最后一个元素的写法tsv_file[len(tsv_file) - 1]可以简化为tsv_file[-1],功能完全一致

内容的提问来源于stack exchange,提问作者Prosy A.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 14:09:02