【问题标题】:Please, help me to convert shell-script to python请帮我将shell脚本转换为python
【发布时间】:2013-01-20 06:48:43
【问题描述】:

我想制作 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()

【问题讨论】:

    标签: python file list dir


    【解决方案1】:

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

    编辑:递归遍历每个目录

    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 命名。如果它存在,它会打印类似“[子目录] 中的文件退出!”的内容。如果不是,它会打印 - “糟糕![子目录] 中没有文件” 我上面的 shell 脚本工作正常。现在我想让我的 python 脚本做同样的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多