问题
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)
However I get results as follows:
> 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
Would someone mind explaining why this is happening and what I'm doing wrong.
other information which may be of use:
> python3.1 --version
Python 3.1.3
> cat /etc/debian_version
6.0.2
回答1:
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
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)]
来源:https://stackoverflow.com/questions/6714491/python-script-to-test-for-most-recently-modified-file-inconsistent-results