开发者

how to get the latest file in the folder

开发者 https://www.devze.com 2023-01-03 19:38 出处:网络
i have written the code to retrieve and file and time it got created by i just want to get the latest file name crea开发者_高级运维ted. Please suggest how can i do that in jython .

i have written the code to retrieve and file and time it got created by i just want to get the latest file name crea开发者_高级运维ted. Please suggest how can i do that in jython .

 import os
    import glob
    import time
    folder='C:/xml'
    for folder in glob.glob(folder):
        for file in glob.glob(folder+'/*.xml'):
            stats=os.stat(file)
            print file ,time.ctime(stats[8])

Thanks again for all your help

I have re-modified the codes as suggested and i am not getting the right answer , Please suggest what mistake i am doing.

import os
import glob
import time
folder='C:/xml'
for x in glob.glob(folder+"/*.xml"):
    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)=os.stat(x)
    time1=time.ctime(mtime)
    for z in glob.glob(folder+"/*.xml"):
        (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)=os.stat(z)
        time2=time.ctime(mtime)
        if (time1>time2):
            new_file=x
            new_time=time1
        else:
            new_file=z
            new_time=time2

print new_file,new_time


Use two variables to keep track of the name and time of the latest file found so far. Whenever you find a later file, update both variables. When your loop is done, the variables will contain the name and time of the latest file.

I'm not quite sure why you have two nested loops in your example code; if you're looking for all *.xml files in the given directory, you only need one loop.

A Pythonic solution might be something like:

folder = "C:/xml"
print max((os.stat(x)[8], x) for x in glob.glob(folder+"/*.xml"))

If you choose the max() solution, be sure to consider the case where there are no *.xml files in your directory.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号