请帮我转换shell脚本到python

时间:2013-02-05 10:59:40

标签: python file list dir

我想让python-script在目录中按模式搜索文件并显示结果。 在shell中它很容易,并且在一小时内完成。

date=`date +%F`
path=/root/bkp
for i in $(ls $path)
do
str=`find $path/$i -name “*$date*.txt”`
if [$str]
    then
        echo “File in $i is OK”
    else
        echo “File in $i is not found”
fi
done

在Python中

import subprocess,os,datetime,fnmatch
path='/root/bkp'
date=datetime.date.today()
pattern=str('%s' %date)
def find_file():
    obj=re.compile(pattern)
    for root,dirs,files in os.walk(path):
        for f in files:
        match=obj.search(f)
            if match:
                print ‘File in ??? is OK’ ===== # need directory mention
            else:
                print ‘no file’
find_file()

1 个答案:

答案 0 :(得分:0)

我对这个问题感到有点困惑,但是如果你只是在寻找文件名中是否有模式,那么你已经在那里了。

编辑:以递归方式遍历每个目录

import os,datetime
path = "C:\\Temp"
date=datetime.date.today()
pattern=str('%s' %date)
filefound = False
def find_file(currpath):
    for dirname, dirnames, filenames in os.walk(currpath):
        for files in filenames:
            if pattern in files:
                print("File found in " + currpath)
                global filefound
                filefound = True
                return
        for directory in dirnames:
           find_file(path+"\\"+directory)
find_file(path)
if filefound == False:
    print("File containing " + pattern + " not found in " + path)