简体   繁体   English

我如何告诉 python 移动到目录中的下一个文件?

[英]How do I tell python to move to the next file in the directory?

How do I move to the next file in Python after checking that the file extension is correct and parsing it in element tree?在检查文件扩展名是否正确并在元素树中解析后,如何移动到 Python 中的下一个文件? See code below.请参阅下面的代码。 After the file is checked for .bpmn and parsed I would like to move to the next file and check if it is an .xml and then parse.检查文件的 .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")

for loops does it for you and continue bypass it. for 循环为您完成并继续绕过它。 The continue statement in Python returns the control to the beginning of the while loop. Python 中的 continue 语句将控制权返回到 while 循环的开头。 The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. continue 语句拒绝循环当前迭代中的所有剩余语句,并将控制移回循环顶部。

The continue statement can be used in both while and for loops. continue 语句可用于 while 和 for 循环。 for filename in os.listdir(path):对于 os.listdir(path) 中的文件名:

so filename keep changing after loop get executed.所以文件名在循环执行后不断变化。 try this.尝试这个。 use continue path = 'path_to_directory'使用继续路径 = '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")

continue继续

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

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

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