Python脚本测试最新修改的文件-结果不一致 [英] Python script to test for most recently modified file - inconsistent results
问题描述
我发现了关于stackoverflow的帖子,这正是我想要集成到我正在编写的更大脚本中的内容:
I found this post on stackoverflow which was exactly what I wanted to integrate into a larger script I am writing: Find the newest folder in a directory in Python
我要检查最新文件或文件夹,因此修改了测试脚本,如下所示:
I want to check for the newest file or folder so modified the script for testing as follows:
#!/usr/bin/env python3.1
import os
def allFilesIn(b='.'):
result = []
for d in os.listdir(b):
bd = os.path.join(b, d)
result.append(bd)
return result
latest_subdir = max(allFilesIn('/tmp/testforlatest'), key=os.path.getmtime)
print(latest_subdir)
但是我得到结果如下:
> touch /tmp/testforlatest/file1
> ls -t -1 /tmp/testforlatest/ | head -1
file1
> /tmp/testfornewestfile.py
/tmp/testforlatest/file1
> touch /tmp/testforlatest/file2
> ls -t -1 /tmp/testforlatest/ | head -1
file2
> /tmp/testfornewestfile.py
/tmp/testforlatest/file1
> mkdir /tmp/testforlatest/folder1
> ls -t -1 /tmp/testforlatest/ | head -1
folder1/
> /tmp/testfornewestfile.py
/tmp/testforlatest/folder1
> mkdir /tmp/testforlatest/folder2
> ls -t -1 /tmp/testforlatest/ | head -1
folder2/
> /tmp/testfornewestfile.py
/tmp/testforlatest/folder1
> touch /tmp/testforlatest/file3
> ls -t -1 /tmp/testforlatest/ | head -1
file3
> /tmp/testfornewestfile.py
/tmp/testforlatest/folder1
有人会介意解释为什么
其他可能有用的信息:
> python3.1 --version
Python 3.1.3
> cat /etc/debian_version
6.0.2
推荐答案
您的函数 allFilesIn
仅返回 os.listdir
返回的最后一个文件,因为您将结果附加到了for循环之外。您可能是这样想的:
Your function allFilesIn
only returns the last file returned by os.listdir
because you append the results outside of the for loop. You probably meant this:
def allFilesIn(b='.'):
result = []
for d in os.listdir(b):
bd = os.path.join(b, d)
result.append(bd)
return result
顺便说一句,对于每个 PEP8 。您也可以很容易地将该函数压缩为列表理解:
As an aside it's preferable to use lowercase and underscores for function names per PEP8. You could also condense the function into a list comprehension pretty easily:
def all_files_in(path='.'):
return [os.path.join(path, f) for f in os.listdir(path)]
这篇关于Python脚本测试最新修改的文件-结果不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!