[英]Please, help me to convert shell-script to python
我想使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
在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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.