请帮助我将shell脚本转换为python
我想让python脚本在目录中按模式搜索文件并显示结果。 在贝壳里,它很容易,一个小时就做成了请帮助我将shell脚本转换为python,python,file,list,dir,Python,File,List,Dir,我想让python脚本在目录中按模式搜索文件并显示结果。 在贝壳里,它很容易,一个小时就做成了 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
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()
我对这个问题有点困惑,但是如果你只是想知道文件名是否有模式,那么你已经差不多有了 编辑:递归地遍历每个目录
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)
谢谢你的帮助,但显然我还不够清楚。目录-/root/bkp:/root/bkp/one/root/bkp/two/root/bkp/three中有子目录,每个子目录中都有按日期命名的文件,例如2013-02-04.txt、2013-02-04.txt、2013-02-05.txt。所以脚本应该检查文件是否存在于子目录中。文件是根据date.today命名的。如果存在,它会打印类似于“退出[subdirectory]中的文件!”的内容;如果不存在,它会打印“哎呀!在[subdirectory]中没有文件”。我上面的shell脚本工作正常。现在我想让我的python脚本也这样做。