Python Forum

Full Version: python 3 find difference between 2 files
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I'm working a file system monitoring script. When I compare two files in the below script, it's returning non-zero value even though both files are same. I checked for any special characters also.
When I run the diff command on shell it shows no difference and echo $? returns zero. Please help me solve this issue.

[root@]# cat fs.txt
home=17
apps=7
work=54

[root@log]# cat apps_WARN_20200514-1210
7
[root@log]# cat apps_WARN_20200514-1211
7

[root@]# ./check_fs_usage.py
0a1
> 7
1


#!/usr/bin/env /opt/anaconda3/bin/python

import datetime
import os
import sys
import subprocess

DT = datetime.datetime.now().strftime("%Y%m%d-%H%M")
FP = '/root/pyscripts/log/'

with open ('/root/pyscripts/log/fs.txt', 'r') as FS:
    for x in FS.readlines():
        if int(x.split('=')[1]) >= 5 and int(x.split('=')[1]) <=10:
            with open(FP + x.split('=')[0] + "_WARN_" + DT, "w") as WF:
                WF.write(x.split('=')[1])
                subprocess.call("ls -1tr | grep " + x.split('=')[0] + "_WARN| head -n -2 | xargs -d '\n' rm -f --", shell=True)
                FN = WF.name
                FN = FN.split('/')[4]
                OldFN = subprocess.check_output("ls -1tr | grep " + x.split('=')[0] + "_WARN | grep -v " + FN, shell=True)
                OldFN = str(OldFN, 'utf-8').strip()
                os.chdir(FP)
                STATUS = subprocess.call('diff ' + FN + ' ' + OldFN, shell=True)
                print(STATUS)
                
I also tried, but same error:
STATUS = subprocess.call('diff ' + x.split("=")[0] + '_WARN*  > /dev/null 2>&1', shell=True)
I tried with filecop module as well. It seems like the issue is with files that are created through the script.
If I create file manually and run it through python script it works.

OldFN = (FP + OldFN)
FN = (FP + FN)
print(FN)
print(OldFN)
STATUS =  filecmp.cmp(OldFN, FN, shallow=False)
you may be experiencing a difference in line terminator.
Before comparing lines, use strip, after line 12, add: x = x.strip()
try that

Actually that's not going to work here, but keep it in mind.