我在不同的文件夹中有几个文本文件。
Southwest (folder)
Texas (folder)
Houston (folder)
11-18-2018 (folder)
Houston.txt (date modified 11-18-2018)
11-11-2018 (folder)
Houston.txt (date modified 11-11-2018)
Austin (folder)
11-18-2018 (folder)
Austin.txt (date modified 11-18-2018)
11-11-2018 (folder)
Austin.txt (date modified 11-11-2018)
Southern_Pacific (folder)
California
San-Diego (folder)
11-18-2018 (folder)
San_Diego.txt (date modified 11-18-2018)
11-11-2018 (folder)
San_Diego.txt (date modified 11-11-2018)
Los_Angeles (folder)
11-18-2018 (folder)
Los_Angeles.txt (date modified 11-18-2018)
11-11-2018 (folder)
Los_Angeles.txt (date modified 11-11-2018)
and so on with other different regions in US.
目标:我需要根据文件夹所在的城市来获取每个文件夹的所有最新文件。因此,返回值将类似于:
C:\Southwest\Texas\Houston\11-18-2018\Houston.txt
C:\Southwest\Texas\Austin\11-18-2018\Austin.txt
C:\Southern_Pacific\California\San_Diego\11-18-2018\San_Diego.txt
C:\Southern_Pacific\California\Los_Angeles\11-18-2018\Los_Angeles.txt
然后,我将使用返回值作为路径来打开文件并通过我构建的另一个函数进行操作。但是此刻,其他功能仅在文件驻留在运行脚本的同一文件夹中,或者我将其专门指向子文件夹而不是整个树时才起作用。
因此,在这一点上,我需要能够浏览每个文件夹,获取每个城市的最新文件,并将该值作为文件的路径返回。
我一般都不熟悉python或脚本。会不胜感激的!
答案 0 :(得分:0)
使用os.walk浏览目录结构,并使用os.path.getmtime确定每个文件的修改时间。
为了比较时间,我建议使用datetime模块。
答案 1 :(得分:0)
这是我为您提供的解决方案:
import os
from datetime import datetime
def getNewestFiles(startpath):
path = ""
currTime = 0
maxTime = 0
resultPath = ""
for root, dirs, files in os.walk(startpath): #search from start to all folders and files
maxTime = 0
resultPath = ""
for f in files:
path = root+"\\"+f
currTime = os.path.getmtime(path) #get time of file
if(currTime > maxTime): #compare time with other files
maxTime = currTime
resultPath = path #take the largest number
if(resultPath != ""):
print('{} : {}'.format(resultPath, datetime.fromtimestamp(float(os.path.getmtime(resultPath))).strftime('%Y-%m-%d %H:%M:%S')))
您必须选择起始路径,然后才能在所有目录中获得所有最新文件