Проверьте, является ли последний файл в 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