检查 os.listdir() 中的最后一个文件是否

Check if the last file in os.listdir()

我需要知道 os.listdir 当前检查的文件是否是最后一个文件。在我拥有的条件下,我需要它。这是代码:

# iterate through all files in directory
for filename in os.listdir(edgar_path):
    # open and read
    with open(edgar_path + filename, '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[len(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:
            logger.debug('pass condition 2')
        # add to delete files if both conditions are unmet
        else:
            files_to_delete.append(filename)
            logger.debug('no pass')

感谢任何帮助。

我想你可以把文件名放在一个列表变量中(下面代码中的filenames)并检查filename是否是filenames列表中的最后一项,方法是使用条件

filename == filenames[-1]
# iterate through all files in directory
filenames = os.listdir(edgar_path)
for filename in filenames:
    # open and read
    with open(edgar_path + filename, '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[len(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:
            logger.debug('pass condition 2')
        # add to delete files if both conditions are unmet
        else:
            files_to_delete.append(filename)
            logger.debug('no pass')
    
    # check for last file here
    if filename == filenames[-1]:
        # Do something