如何获取文件夹中最新的文件
我已经编写了代码来检索和文件及其创建时间,我只想获取创建的最新文件名。请建议我如何在 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])
再次感谢您的帮助,
我已按照建议重新修改了代码,但没有得到正确的答案,请建议我犯了什么错误。
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
i have written the code to retrieve and file and time it got created by i just want to get the latest file name created. 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用两个变量来跟踪迄今为止找到的最新文件的名称和时间。每当您找到稍后文件时,请更新这两个变量。循环完成后,变量将包含最新文件的名称和时间。
我不太确定为什么示例代码中有两个嵌套循环;如果您要查找给定目录中的所有
*.xml
文件,则只需要一个循环。Pythonic 解决方案可能类似于:
如果您选择
max()
解决方案,请务必考虑没有*.xml
的情况> 您目录中的文件。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:
If you choose the
max()
solution, be sure to consider the case where there are no*.xml
files in your directory.