在python中查找最近编辑的文件
我有一组文件夹,我希望能够运行一个函数来查找最近编辑的文件并告诉我该文件的名称及其所在的文件夹。
文件夹布局:
root
Folder A
File A
File B
Folder B
File C
File D
etc...
任何让我开始的提示我碰壁了。
I have a set of folders, and I want to be able to run a function that will find the most recently edited file and tell me the name of the file and the folder it is in.
Folder layout:
root
Folder A
File A
File B
Folder B
File C
File D
etc...
Any tips to get me started as i've hit a bit of a wall.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您应该查看 os.walk 函数,以及 < a href="http://docs.python.org/library/os.html#os.stat" rel="nofollow noreferrer">os.stat,它可以让你执行以下操作:
You should look at the os.walk function, as well as os.stat, which can let you do something like:
它有助于将内置目录遍历包装为仅生成文件的完整路径的函数。然后,您可以使用返回所有文件的函数并选出修改时间最长的文件:
It helps to wrap the built in directory walking to function that yields only full paths to files. Then you can just take the function that returns all files and pick out the one that has the highest modification time:
如果有人正在寻找一种单行方法来做到这一点:
If anyone is looking for an one line way to do it:
对于多个文件,如果有人来这里:
这将打印
/path/
内任何文件夹中具有.mp4
扩展名的所有文件,以及最近修改的文件底部的路径。For multiple files, if anyone came here for that:
This will print all files in any folder within
/path/
that have the.mp4
extension, with the most recently modified file paths at the bottom.您可以使用
参见:http://docs.python.org/library/os.html
You can use
See: http://docs.python.org/library/os.html
使用
os.path.walk()
< /a> 遍历目录树和os.stat().st_mtime< /code>
获取文件的 mtime。
您传递给 os.path.walk() 的函数(
visit
参数)只需要跟踪它所看到的最大 mtime 以及它在哪里看到的。Use
os.path.walk()
to traverse the directory tree andos.stat().st_mtime
to get the mtime of the files.The function you pass to
os.path.walk()
(thevisit
parameter) just needs to keep track of the largest mtime it's seen and where it saw it.我正在使用
path = r"C:\Users\traveler\Desktop"
:我在这里缺少什么?
I'm using
path = r"C:\Users\traveler\Desktop"
:What am i missing here?