返回目录中每个文件夹的最新文件

2024-07-04 09:08:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个文本文件位于不同的文件夹。你知道吗

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或脚本都是新手。请伸出援助之手!你知道吗


Tags: 文件txt文件夹datefoldermodifiedsanaustin
2条回答

使用os.walk导航目录结构,使用os.path.getmtime确定每个文件的修改时间。你知道吗

为了比较时间,我建议使用datetime模块。你知道吗

以下是我给你的解决方案:

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')))

你必须选择你的开始路径,然后你得到所有目录中的所有最新文件

相关问题 更多 >

    热门问题