![](/img/trans.png)
[英]Python - How can I create multiple folders in a newly created directory?
[英]Python: How can i find new folders/directories created in last hour in a specific directory in Linux
我正在尝试编写一个Python程序,该程序调用bash脚本以在目录中的新数据上运行。
我的目录中有数百个子目录。 每小时生成几个子目录。 我试图进入这些新的子目录,并对其中的数据运行脚本。
可以说我目录的路径是/ data1 / realtime:
在“实时”目录中,每小时产生一个新的子目录。 我怎么知道每小时产生一个新的子目录,并逐个进入其中的每个..?
非常感谢!!
佳日
您可以使用os.listdir设置进行比较:
import os
path = "."
prev = [d for d in os.listdir(".") if os.path.isdir(os.path.join(path,d))]
os.mkdir("foo")
curr = [d for d in os.listdir(".") if os.path.isdir(os.path.join(path,d))]
new = set([d for d in os.listdir(".") if os.path.isdir(os.path.join(path,d))]).difference(prev)
for d in new:
print(new)
使用find
命令(在您的shell中):
find /data1/realtime -mmin -60 -type d
它将打印最近60分钟内已创建或已添加,删除或重命名文件或子目录的所有目录。
当然,如果需要,您当然可以从Python的subprocess
模块中调用它,但是由于您已经在使用bash,也许您可以直接在bash脚本中使用它?
这是使用subprocess
调用find的方法:
import subprocess
directories = subprocess.check_output(
['find', '/data1/realtime', '-type', 'd', '-mmin', '-60']
).splitlines()
# directories content: ['/data1/realtime/dir1000', ...]
这可能会捕获正在创建的目录,如msw在注释中所述,因此,如果要查找在最近一小时内创建的目录,但不要在5分钟前创建,则可以添加另一个测试来find
:
find /data1/realtime -mmin -60 -mmin +5 -type d
为了了解其工作原理,下面是一个bash会话:
$ find --version
find (GNU findutils) 4.4.2
...
$ mkdir /tmp/test
$ cd /tmp/test
$ date
Mon Feb 9 21:27:00 CET 2015
$ touch a
$ touch -t 02092100 b # 27 minutes ago
$ touch -t 02082100 c # yesterday
$ ls -alh
total 0
drwxr-xr-x 2 andre andre 100 Feb 9 21:27 .
drwxrwxrwt 24 root root 520 Feb 9 21:26 ..
-rw-r--r-- 1 andre andre 0 Feb 9 21:27 a
-rw-r--r-- 1 andre andre 0 Feb 9 21:00 b
-rw-r--r-- 1 andre andre 0 Feb 8 21:00 c
$ find . -mmin -60 -mmin +5
./b
不出所料,新创建的文件(a)和昨天的文件(c)被排除,但包含27分钟前更新的文件(b)。 如果你是这样,这应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.