【问题标题】:How do I tell python to move to the next file in the directory?如何告诉 python 移动到目录中的下一个文件?
【发布时间】:2019-12-09 18:10:06
【问题描述】:

在检查文件扩展名是否正确并在元素树中解析后,如何在 Python 中移动到下一个文件?请参阅下面的代码。在检查文件的 .bpmn 并解析后,我想移动到下一个文件并检查它是否是 .xml 然后解析。

path = 'path_to_directory'
for filename in os.listdir(path):
    if filename.endswith(".bpmn"):
        fullname = os.path.join(path, filename)
        tree = ET.parse(fullname)
        root = tree.getroot()

     else:
         print("must end with .bpmn")

    if filename.endswith(".xml"):
        fullname = os.path.join(path, filename)
        treeXML = ET.parse(fullname)
        rootXML = treeXML.getroot()
     else:
        print("must end with xml")

【问题讨论】:

  • 这就是循环的用途。它们将自动移动到源迭代中的下一项。

标签: python elementtree


【解决方案1】:

for 循环会为您完成并继续绕过它。 Python 中的 continue 语句将控制权返回到 while 循环的开头。 continue 语句拒绝当前循环迭代中的所有剩余语句,并将控件移回循环顶部。

continue 语句可用于 while 和 for 循环。 对于 os.listdir(path) 中的文件名:

所以循环执行后文件名不断变化。 尝试这个。 使用继续 path = 'path_to_directory'

for filename in os.listdir(path):
    if filename.endswith(".bpmn"):
        fullname = os.path.join(path, filename)
        tree = ET.parse(fullname)
        root = tree.getroot()
        continue
     else:
         print("must end with .bpmn")

    if filename.endswith(".xml"):
        fullname = os.path.join(path, filename)
        treeXML = ET.parse(fullname)
        rootXML = treeXML.getroot()
        continue
     else:
        print("must end with xml")

继续

import os, sys

# Open a file
path = "/var/www/html/"
dirs = os.listdir( path )

# This would print all the files and directories
for file in dirs:
   print file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-21
    • 2019-09-26
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2017-07-20
    相关资源
    最近更新 更多