0
votes

I am new to python. I am writing a python script to find the diff between 2 html file1: beta.vidup.me-log-2016-09-21-17:43:28.html and file2: beta.vidup.me-log-2016-09-21-17:47:48.html.

To give an idea about my file organization: I have 2 directories 2016-09-21 and 2016-09-22. file1: beta.vidup.me-log-2016-09-21-17:43:28.html is present in dir1 and file2: beta.vidup.me-log-2016-09-21-17:47:48.html is present in dir2.

Below is my snippet:

dir1 = raw_input("Enter date of Archive folder to compare with in format yyyy-mm-dd---->\n")
dir2 = raw_input("Enter date of folder to compare in format yyyy-mm-dd----->\n")

now = datetime.now()
folder_output = '/home/diff_output/{}'.format(now.strftime('%Y-%m-%d'))

mkdir(folder_output)

fname1 = '/home/output/%s/beta.vidup.me-log-2016-09-21-17:43:28.html'%dir1
fname2 = '/home/output/%s/beta.vidup.me-log-2016-09-21-17:47:48.html'%dir2

# Open file for reading in text mode (default mode)
f1 = open(fname1)
f2 = open(fname2)

cmd = "diff "+fname1+'\t'+fname2
curl = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)

file_data = curl.stdout.read()
print file_data

fname1.close()
fname2.close()

I wish to perform diff using the subprocess module only.

I want my code to take fname1 from dir1 and fname2 from dir2 and perform the diff and output it to a folder and Loop back to pick the next file in dir1 for fname1 and next file from dir2 for fname2 and perform the diff again.

Thanks for your time and advice in advance.

1
Do you have a question? See How to Ask. - Peter Wood
My apologies. I edited my question - nits
You don't need to open the files. Also, it should be f1.close(), not fname1.close(). - Barmar

1 Answers

0
votes

Below are the functions you need with examples. Merge them using the logic with for loop.

You can use subprocess.check_output() to get output from the command. Try:

cmd = ["diff", fname1, +fname2]
output = subprocess.check_output(cmd)
print output

if you want to write this to file:

with open('/paht/to/file', 'w+') as f:
    f.write(output)

In order to get list of files in directory, use listdir(), isfile and join functions of os module. For example:

from os import listdir
from os.path import isfile, join
only_files = [f for f in listdir('path') if isfile(join('path', f))]
# only_files will contain list of all files in 'path' path

As you mentioned, you don't have much idea on loop. To give you the basic idea on how your loop should work. Below is the example (instead of copying, try to understand each line. it'll be helpful for you in future):

for f1, f2 in zip(file_list_1, file_list_2): # takes first, second, etc files corresponding to each list 
    output = subprocess.check_output(['diff', f1, f2]) # generate diff of both file
    with open('diff-{}-{}'.format(f1, f2), 'w+') as f:
        f.write(output)  # write the diff to third file

Modify the above logic as per your requirement.