I have the following loop which is parsing the outputs of a difflib comparison of 2 configuration files and, so far showing me the differences in file 2 (indicated with +) and the heading in the file that the difference falls under e.g. [server]
code:
#!/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)
**Example Output:-**
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]
what I'm trying to do is only print a heading (e.g [server] ) if the next element in the list begins with + thereby excluding the headers that have no deltas under them'
on other words for the line with the header to print 2 conditions must be met: 1. the line must begin with [ 2. the next line must begin with +
for example:
[server]
+ # web-host-name = www.myhost.com
+ https-port = 1080
+ network-interface = 0.0.0.0
[session]
+ preserve-inactivity-timeout = 330
To achieve this I've tried changing the above for loop to the following:
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)
However, this results in the following error:
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
Aucun commentaire:
Enregistrer un commentaire