Obtain the difference between two files
<p><em>First of all, i searched on the web and stackoverflow for around 3 days and haven't found anything i've been looking for.</em></p>

<p>I am doing a weekly security audit where i get back a .csv file with the IPs and the open ports. They look like this:</p>

<p><strong>20160929.csv</strong></p>

<pre><code>10.4.0.23;22
10.12.7.8;23
10.18.3.192;23
</code></pre>

<p><strong>20161006.csv</strong></p>

<pre><code>10.4.0.23;22
10.18.3.192;23
10.24.0.2;22
10.75.1.0;23
</code></pre>

<p>The difference is:
<strong>10.12.7.8:23</strong> got closed.
<strong>10.24.0.2:22</strong> and <strong>10.75.1.0:23</strong> got opened.</p>

<p>I want a script which prints me out:</p>

<pre><code>[-] 10.12.7.8:23
[+] 10.24.0.2:22
[+] 10.75.1.0:23
</code></pre>

<p><strong>How can i make a script like this?</strong> I tried my difflib but that isn't what i need. I need to be able to also write that to files later or send that output as a mail which i have a script for already.</p>

<p>I can't use Unix, because in our company we have a Windows environment and are not allowed to use another OS. So i can't use <code>diff</code> or some other great tools.</p>

<p>This is my first attempt:</p>

<pre><code>old = set((line.strip() for line in open('1.txt', 'r+')))
new = open('2.txt', 'r+')
diff = open('diff.txt', 'w')

for line in new:
    if line.strip() not in old:
        diff.write(line)
new.close()
diff.close()
</code></pre>

<p>This is my second attempt</p>

<pre><code>old = set((line.strip() for line in open('1.txt', 'r+')))
new = open('2.txt', 'r+')
diff = open('diff.txt', 'w')

for line in new:
    if line.strip() not in old:
        diff.write(line)
new.close()
diff.close()
</code></pre>

<p>In the following solution I've used sets, so the order doesn't matter and we can do direct subtraction with the old and new to see what has changed.</p>

<p>I've also used the <code>with</code> context manager pattern for opening files, which is a neat way of ensuring they are closed again.</p>

<pre><code>def read_items(filename):
    with open(filename) as fh:
        return {line.strip() for line in fh}

def diff_string(old, new):
    return "\n".join(
        ['[-] %s' % gone for gone in old - new] +
        ['[+] %s' % added for added in new - old]
    )

with open('diff.txt', 'w') as fh:
    fh.write(diff_string(read_items('1.txt'), read_items('2.txt')))
</code></pre>

<p>Obviously you could print out the diff string if you wanted to.</p>

python python-2.7 csv difference differentiation