我知道如何列出目录树中所有子目录和文件。但是我正在寻找一种方法,可以列出从根目录开始的目录树中所有目录中新创建、修改(如果可能)和删除的文件。
我知道如何列出目录树中所有子目录和文件。但是我正在寻找一种方法,可以列出从根目录开始的目录树中所有目录中新创建、修改(如果可能)和删除的文件。
您可以通过查看每个文件的“mtime”来找到在过去半个小时内创建或修改的所有文件:
import os
import datetime as dt
now = dt.datetime.now()
ago = now-dt.timedelta(minutes=30)
for root, dirs,files in os.walk('.'):
for fname in files:
path = os.path.join(root, fname)
st = os.stat(path)
mtime = dt.datetime.fromtimestamp(st.st_mtime)
if mtime > ago:
print('%s modified %s'%(path, mtime))
要生成已删除文件的列表,你还需要拥有30分钟前文件的列表。
更可靠的替代方案是使用版本控制系统,比如 git
。将目录中所有文件提交为一个commit就像拍摄一张快照。然后使用以下命令:
git status -s
会列出自上次提交以来发生更改的所有文件,这也会列出已删除的文件。
str.format
在Python2.6中引入。对于早期版本,您可以使用%s
风格的字符串格式化。我将编辑我的帖子以展示我的意思。 - unutbufrom tempfile import mkstemp
import shutil
import os
import datetime as dt
import sys
# gets the time frame we are going to look back and builds a placeholder list to passover the info from our mtime to slay
now=dt.datetime.now()
ago=now-dt.timedelta(minutes=480)
passover=[]
# the '.' is the directory we want to look in leave it to '.' if you want to search the directory the file currently resides in
for root,dirs,files in os.walk('.'):
for fname in files:
path=os.path.join(root,fname)
st=os.stat(path)
mtime=dt.datetime.fromtimestamp(st.st_mtime)
if mtime>ago:
passover.append(path)
def slay(file_path, pattern, subst):
#Create temp file
fh, abs_path = mkstemp()
with open(abs_path,'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
new_file.write(line.replace(pattern, subst))
old_file.close()
#Remove original file
os.remove(file_path)
#Move new file
try:
shutil.move(abs_path, file_path)
except WindowsError:
pass
#we pass the passover list to the slay command in a for loop in order to do muiltple replaces in those files.
for i in passover:
slay(i,"String1","String2")
看一下"man find"
创建一个临时文件进行比较
例如:
find / -type f -newerB tempFile
man find的某些部分
-newerXY reference
Compares the timestamp of the current file with reference. The reference argument is normally the name of a file (and one
of its timestamps is used for the comparison) but it may also be a string describing an absolute time. X and Y are place‐
holders for other letters, and these letters select which time belonging to how reference is used for the comparison.
a The access time of the file reference
B The birth time of the file reference
c The inode status change time of reference
m The modification time of the file reference
t reference is interpreted directly as a time
os.lstat
来访问文件属性呢? - hochlst=os.lstat(filepath)
和st.st_mtime
字段,并检查与当前时间的差是否小于1800。就这样。 - hochl