无法从上一个eli获取输出

2024-09-30 01:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试迭代目录中的一堆.xml文件。你知道吗

为此,我编写了一个python脚本:

#!/usr/bin/python3.5

import os
import glob

pathToDirectory = '/home/anton/Documents/Repo_from_GitHub/ResiShared/templates/'

for filename in os.listdir(pathToDirectory):
    file = open(pathToDirectory.__add__(filename), "r")
    count = 0
    for line in file:
        if line.__contains__('xmlns="http://xml.juniper.net/xnm/1.1/xnm"') \
                | line.__contains__('xmlns="http://tail-f.com/ned/cisco-ios-xr"') \
                | line.__contains__('xmlns="http://tail-f.com/ned/arista-dcs"'):
            ++count
        elif line.__contains__('tags="replace"'):
            --count
        elif (line.__contains__('</config>') \
                | line.__contains__('</config-template>')) & count > 0:
                    print ('There are ' + str(count) + ' tags="replace" missing in the ' + file.name)

它是工作没有任何错误发现,但我也没有从最后一个“elif”输出,但它肯定应该是。你知道吗

以下是.xml文件的示例: xml file example

更新: 我不需要任何类型的XML解析器,Python的核心功能应该足够了。你知道吗


Tags: 文件inimporthttpforoscountline
2条回答

正如buran指出的,python中没有++操作符,因此count的值保持为0。更改以下内容可以解决您的问题:

++count应该是count += 1

count应该是count -= 1

|符号是按位运算符,而应该使用or。你知道吗

python不支持++运算符。因此,当您执行++count count时,count的值不会发生任何变化,count > 0始终是False。你知道吗

注意它不会引发异常,因为它是一个有效的代码。++count实际上是在一行中应用一元运算符+两次(即+(+count))。与-(-count))相同。你知道吗

给定xml示例文件,您希望line.__contains__('</config-template>')) & count > 0True,但事实并非如此。你知道吗

所有这些-我同意@King'sjester的评论,以及为什么您直接调用像__contain__()这样的dunder方法?它使代码的可读性降低,至少说起来不那么难看。我会接受@mannojlds的建议,寻找更多pythonic工具来解析xml文件。你知道吗

>>> line = 'spam'
>>> count = 0
>>> line.__contains__('eggs') & count > 0
False

编辑成包含一元运算符的解释。你知道吗

相关问题 更多 >

    热门问题