我正在尝试找到一个带有' .tmp'的文件夹。目录及其所有子目录(及其所有后续子目录)中的扩展名。基本上是一个带有' .tmp'的文件夹。在特定路径中的任何地方扩展。
截至目前,我只能在特定目录中找到扩展名为.tmp的文件夹,但不能在其后续目录中找到。请帮助。
代码:
def main():
"""The first function to be executed.
Changes the directory. In a particular directory and subdirectories, find
all the folders ending with .tmp extension and notify the user that it is
existing from a particular date.
"""
body = "Email body"
subject = "Subject for the email"
to_email = "subburat@synopsys.com"
# Change the directory
os.chdir('/remote/us01home53/subburat/cn-alert/')
# print [name for name in os.listdir(".") if os.path.isdir(name)]
for name in os.listdir("."):
if os.path.isdir(name):
now = time.time()
if name.endswith('.tmp'):
if (now - os.path.getmtime(name)) > (1*60*60):
print('%s folder is older. Created at %s' %
(name, os.path.getmtime(name)))
print('Sending email...')
send_email(body, subject, to_email)
print('Email sent.')
if __name__ == '__main__':
main()
操作系统:Linux; 编程语言Python
答案 0 :(得分:3)
由于您使用的是Python 3.x,因此可以尝试pathlib.Path.rglob
pathlib.Path('.').rglob('*.tmp')
修改强>
我忘了添加每个结果将是 pathlib.Path 子类的实例,因此整个目录选择应该像那样简单
[p.is_dir() for p in pathlib.Path('.').rglob('*.tmp')]
答案 1 :(得分:2)
存在一些关于递归列出文件的现有问题。他们确实通过使用glob模块来实现这个功能。以下是一个例子。
import glob
files = glob.glob(PATH + '/**/*.tmp', recursive=True)
PATH是从中开始搜索的根目录。
(改编自answer。)
答案 2 :(得分:1)
如果您使用现有代码并将搜索拆分为自己的函数,则可以递归调用它:
def find_tmp(path_):
for name in os.listdir(path_):
full_name = os.path.join(path_, name)
if os.path.isdir(full_name):
if name.endswith('.tmp'):
print("found: {0}".format(full_name))
# your other operations
find_tmp(full_name)
def main():
...
find_tmp('.')
这将允许您检查每个结果目录以查找更多子目录。
答案 3 :(得分:0)
在你的程序中,如果遇到没有"。"的项目,那么你可能会认为它是一个目录(如果没有,这将无效)。将此路径/名称放在Stack类似的数据结构上,一旦完成当前目录,抓住堆栈的顶部并执行相同的操作。
答案 4 :(得分:0)
我能够使用.tmp
方法查找以os.walk()
结尾的所有目录。
下面显示的是我用来完成此操作的代码:
import os
import time
import sys
def send_email(body, subject, to_email):
"""This function sends an email
Args:
body (str): Body of email
subject (str): Subject of email
to_email (str): Recepient (receiver) of email
Returns:
An email to the receiver with the given subject and body.
"""
return os.system('printf "' + body + '" | mail -s "'
+ subject + '" ' + to_email)
def find_tmp(path_):
"""
In a particular directory and subdirectories, find all the folders ending
with .tmp extension and notify the user that it is existing from a
particular date.
"""
subject = 'Clarity now scan not finished.'
body = ''
emails = ['xyz@example.com']
now = time.time()
for root, dirs, files in os.walk(".", topdown=True):
for dir_name in dirs:
if dir_name.endswith('.tmp'):
full_path = os.path.join(root, dir_name)
mtime = os.stat(full_path).st_mtime
if (now - mtime) > (1*60):
body += full_path + '\n'
# Send email to all the people in email list
for email in emails:
print('Sending email..')
send_email(body, subject, email)
print('Email sent')
def main():
find_tmp('.')
if __name__ == '__main__':
main()