如何编写代码,根据修改的最新日期自动打开目录中的最新文件



在Python中,我必须编写一段代码,从目录中选择一个以特定字符串&有多个文件具有相同的名称,我需要根据日期修改最新的。Foe示例我有一个名为的文件

StockPriceReport06112018.pdf    #First saved report in the mrng
StockPriceReport06112018(2).pdf #Updated report saved in same folder in the aftn
StockPriceReport06112018(3).pdf #Updated report saved in same folder in the evening

如何编写代码来自动打开最新的文件

如果您想以所提供的格式打开版本号最大的文件,您可以继续尝试打开版本号越来越大的文件,直到该文件不存在并收到FileNotFoundError为止。

try:
version = ''
version_number = None
with open('file_name%s.pdf' % version) as f:
pass
version_number = 1
while True:
with open('file_name(%s).pdf' % version_number) as f:
pass
version_number += 1
except FileNotFoundError:
if version_number is None:
latest_file_name = 'file_name%s.pdf' % version
else:
latest_file_name = 'file_name(%s).pdf' % version

这假设您的文件版本号是一个连续的范围,这意味着您的文件夹中没有丢失文件的特定版本。因此,要查找file(3).pdf,需要将file.pdffile(2).pdf存储在同一个文件夹中。

我会根据机器文件系统上的修改时间打开文件。这包括执行递归文件列表,然后对每个文件调用stat()以检索上次修改的日期:

编辑:我读错了这个问题,你实际上想要最新的文件(我找到了最旧的(

import os
import sys
import glob
DIRECTORY='.'
### Builds a recursive file list, with optional wildcard match
### sorted so that the oldest file is first.
### Returns the name of the oldest file.
def getNewestFilename(path, wildcard='*'):
age_list = []
# Make a list of [ <modified-time>, <filename> ]
for filename in [y for x in os.walk(path) for y in glob.glob(os.path.join(x[0], wildcard))]:
modified_time = os.stat(filename).st_mtime
age_list.append([modified_time, filename])
# Sort the result, oldest-first
age_list.sort(reverse=True)
if (len(age_list) > 0):
return age_list[0][1]
else:
return None

latest_file = getNewestFilename(DIRECTORY, 'StockPriceReport*.pdf')
if (latest_file != None):
print("Newest file is [%s]" % (latest_file))
data = open(latest_file, "rb").read()
# ...
else :
print("No Files")

最新更新