我有一个函数可以从 XML 文件中读取某些标签。我试图做到这一点,以便如果标签不存在(标签分配的变量失败),则会调用异常并将文件移动到不同的目录并读入下一个文件。
这是我的功能:
def iterateOverXml():
localPath = "C:\local"
remotePath = "C:\outbox"
errorPath = "C:\Error"
xmlFiles = glob.glob1(localPath,"*.xml")
for file in xmlFiles:
print file
a = os.path.join(localPath,file)
element = etree.parse(a)
try:
data= element.xpath('//Foobar/Data/node()')
parsedData = [{field.tag: field.text for field in data} for action in data]
xmlType = parsedData[0]['FormType']
except:
shutil.move(os.path.join(localPath,file),errorPath)
if xmlType == 'record':
parseTitle(element)
parseTracks(element)
parseArtist(element)
shutil.move(os.path.join(localPath,file),remotePath)
如果遇到异常,我怎样才能做到既移动文件又停止当前迭代并调用下一个文件?
最佳答案
How can I make it so if the exception is met it both moves the file and skips to the next file?
只需使用继续
:
for file in xmlFiles:
# ...
try:
# ....
except:
shutil.move(os.path.join(localPath,file),errorPath)
continue # <---- Will continue at the top of the for loop
# with the next file in xmlFiles
关于python - 如果遇到异常则跳过 XML 读取循环的迭代 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9706149/