繁体   English   中英

找不到文件时提高os.walk

[英]Raise os.walk when file not found

如果在文件中找不到“密钥”,我希望脚本停止运行。 如果我的目录看起来像这样:

Dir
   ->file.xml
   ->file2.xml
   ->yyy.m
   ->ignoreTXT.txt
   ->ignoreC.c
   ->ignoreANYTHING.anything
   ->Dir2 -> file3.xml, xxx.m, yyy.m

假设我的json文件中有两个键: "Hello""World"如果在file2.xmlxxx.m找到键"Hello" ,它应该打印出来并继续使用下一个键。 如果没有找到"World" ,它应该给出一个Exception

第一个问题是我的脚本浏览其他文件(例如.txt.c等)。 我想忽略它们,但我不想使用os.remove因为它将删除文件,我需要它们。 还有其他选择吗? 因为由于这个原因,我的“提升异常”将给出错误,因为在.txt文件中找不到"Hello" (我不关心)。

第二个问题是,即使发现"Hello" ,它也会给我一个错误,因为它在file.xmlfile3.xmlignoreTXT.txtignoreC.txt等中找不到任何内容。

jdata = json.load(open(json_path))
path = findAllFiles(directory)

if os.path.isdir(path):
    for root, dirs, files in os.walk(path):
        for key, value in jdata.iteritems():
            for name in files:
                with open(os.path.join(root, name)) as fle:
                    content = fle.read()
                if name.endswith('.txt') and re.search(Wordboundry(key), content):
                    print "Name", key, "was found in", name, "\n"
                    writeToFile(value, content, name, key)
               else:
                   print "Name", key, "was not found in", name
    else:
        raise Exception(key, "was not found in", root) #This gives me error even though "Hello" can be found in file2.xml. 



def FindName(content, key, name, value):
    if name.endswith('.xml') and re.search(Wordboundry(key), content):
        print "Name", key, "was found in", name, "\n"
        OverrideXML(key, value, name)
    elifif name.endswith('.m') and re.search(Wordboundry(key), content):
        print "Name", key, "was found in", name, "\n"
        OverrideM(key, value, name)

您可以非常轻松地过滤掉非.xml文件,如下所示:

if os.path.isdir(path):
    for root, dirs, files in os.walk(path):

        xmlFiles = [file for file in files if file.endswith(".xml")]

        for key, value in jdata.iteritems():
            for name in xmlFiles:
                ...

这将创建一个files子列表,其中仅包含以xml文件扩展名结尾的名称。 然后,您可以循环浏览此子列表以进行搜索

你把else弄错了。 这将有效:

if os.path.isdir(path):
    for root, dirs, files in os.walk(path):
        for key, value in jdata.iteritems():
            for name in files:
                if not name.endswith('.txt'):
                    continue
                with open(os.path.join(root, name)) as fle:
                    content = fle.read()
                if re.search(Wordboundry(key), content):
                    print "Name", key, "was found in", name, "\n"
                    writeToFile(value, content, name, key)
                else:
                    print "Name", key, "was not found in", name
                    raise Exception(key, "was not found in", root)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM