在 for 循环中的条件中使用列表中的下一项



>我有以下循环,它解析了 2 个配置文件的 difflib 比较的输出,到目前为止,向我展示了文件 2 中的差异(用 + 表示)和文件中的标题 差异属于例如 [服务器]

法典:

#!/usr/bin/env python
import difflib
from difflib import Differ
conf = open('C:/Users/fitzs/Documents/Scripts/example_ISAM_conf_file.txt', 'r')
upconf = open('C:/Users/fitzs/Documents/Scripts/Updated_ISAM_conf_file.txt', 'r')
d = difflib.Differ()
diff = list(d.compare(conf.readlines(), upconf.readlines()))# creates a 'generator' list of diffs
delta = ''.join(diff).strip('# ') #converts the list to string

for x in diff:
x = str(x).strip()
if x.startswith('+'):
print(x)
elif x.startswith('['):
print(x)

示例输出:-

The above code is giving me the following example output so far.  
[server]
+ # web-host-name = www.myhost.com
+ https-port = 1080
+ network-interface = 0.0.0.0
[process-root-filter]
[validate-headers]
[interfaces]
[header-names]
[oauth]
[tfim-cluster:oauth-cluster]
[session]
+ preserve-inactivity-timeout = 330
[session-http-headers]

我正在尝试做的是仅在列表中的下一个元素以 + 开头时打印一个标题(例如 [server]),从而排除其下没有增量的标题'

换句话说,对于带有标题的行必须满足 2 个条件: 1. 该行必须以 [ 2. 下一行必须以 + 开头

例如:

[server]
+ # web-host-name = www.myhost.com
+ https-port = 1080
+ network-interface = 0.0.0.0
[session]
+ preserve-inactivity-timeout = 330

为此,我尝试将上面的 for 循环更改为以下内容:

for x in range(0, len(diff)):
stanza = diff[x+1]
x = str(x).strip()
if x.startswith('+'):
print(x)
elif x.startswith('[') and stanza.startswith('+'):
print(x)

但是,这会导致以下错误:

Traceback (most recent call last):
File "C:/Users/fitzs/PycharmProjects/Pydiffer/Pydiffer.py", line 35, in <module>
stanza = diff[x+1]
IndexError: list index out of range

感谢您的以下建议,我已经更新了我的代码如下,它现在可以运行并且没有错误。 但是,索引似乎在循环中返回,而不是实际行本身:

我的 for 循环现在看起来像:-

for x in range(0, (len(diff) - 1)):
# print (diff)
y = str(x)
print (x) 
z = diff[x+1]
if y.startswith('+'):
print(y)
elif y.startswith('[') and z.startswith('+'): 
print(y)

我没有浏览您的脚本,但是可以将for循环更改为以下内容来解决错误

for x in range(0, (len(diff)-1):

您收到该错误是因为stanze=diff[x+1]您正在请求一个不存在的 len(diff)+1 元素。

错误的主要原因是当x = len(diff), stanza = diff[x+1]超出索引时,因为x+1等于(len(diff) +1)。请使用range(len(diff)-1)range(0,len(diff)-1)

最新更新