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



检查文件扩展名是否正确并在元素树中解析后,如何移动到 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")

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

继续语句可以在 while 和 for 循环中使用。 对于 os.listdir(路径(中的文件名:

所以在循环执行后文件名不断变化。 试试这个。 使用继续 路径 = '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

相关内容

最新更新