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



我需要知道当前文件是否在操作系统中检查。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

相关内容