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>Using your code as a base, you could do the following:</p>

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

with open('diff.txt', 'w') as diff:
    for line in new:
        if line not in old:
            diff.write('[-] {}\n'.format(line))

    for line in old:
        if line not in new:
            diff.write('[+] {}\n'.format(line))
</code></pre>

<p>There's a couple of tweaks in here:</p>

<ol>
<li>We want to read the individual lines of both the old and new
files to compare.</li>
<li>We don't have to <code>strip</code> each individual line as we have done that while reading the file.</li>
<li>We use <code>{}</code> and <code>.format()</code> to build text strings.</li>
<li>Using <code>\n</code> ensures we put each entry on a new line of our output file.</li>
<li>Using <code>with</code> for the file we are writing to lets us open it without having to call <code>close</code> and (if my knowledge is correct) allows for better handling of any program crashes once the file has been opened.</li>
</ol>

python python-2.7 csv difference differentiation