Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare the modified date of two files in python?

Tags:

python

I am creating a python script that will access each line from a Text file(say File.txt) one by one then search for corresponding '.py' and '.txt' file in the system directory. For example if "COPY"(the first line) is accessed from "File.txt" then search will be done for "COPY.py" and "COPY.txt". If both the files are found then their modification date will be compared. Code have no syntax error But I am getting the wrong output.

My Python code is:

for line in fileinput.input(r'D:\Python_Programs\File.txt'):
    line = line[0:-1]
    sc = ''.join((line,'.py'))
    lo = ''.join((line,'.txt'))
    for root, dirs, files in os.walk(r'D:\txt and py'):
        if sc in files:
            pytime = time.ctime(os.path.getmtime(os.path.join(root, sc)))
            print(sc, '   :', pytime)
            for root, dirs, files in os.walk(root):
                if txt in files:
                    txttime = time.ctime(os.path.getmtime(os.path.join(root, txt)))
                    print(txt, '  :', txttime)
                    if (txttime > pytime):
                        print('PASS', '\n')
                    else:
                        print('FAIL', '\n')

Output:

COPY.py     : Mon Aug 27 10:50:06 2012
COPY.txt    : Mon Feb 04 11:05:31 2013
PASS        #Expected = PASS

COPY2.py    : Fri Feb 08 16:34:43 2013
COPY2.txt   : Sat Sep 22 14:19:32 2012
PASS        #Expected = FAIL

COPY3.py    : Fri Feb 08 16:34:53 2013
COPY3.txt   : Mon Sep 24 00:50:07 2012
PASS        #Expected = FAIL

I am not getting why "COPY2" and "COPY3" are giving "PASS". May be I am doing it in a wrong way. As well as on changing the comparison as "if (txttime < pytime)" in the code. All results are showing as "FAIL" in output.

like image 523
AshA Avatar asked Feb 08 '13 19:02

AshA


People also ask

How do I compare two dates in Python?

Use datetime. date() to compare two dates Call datetime. date(year, month, day) twice to create two datetime. date objects representing the dates of year , month , and day . Use the built-in comparison operators (e.g. < , > , == ) to compare them.

How do I compare two file names in Python?

cmp(f1, f2, shallow=True) This function compares the two files and returns True if they are identical, False otherwise. The shallow parameter is True by default.


1 Answers

time.ctime() formats a time as a string, so you're comparing the strings "Fri Feb 08 16:34:43 2013" and "Sat Sep 22 14:19:32 2012" textually. Just don't do that and compare the floats that getmtime() gives you directly:

pytime = os.path.getmtime(os.path.join(root, sc))
# ...
txttime = os.path.getmtime(os.path.join(root, txt))
# ...
if (txttime > pytime):
    # ...
like image 126
millimoose Avatar answered Sep 19 '22 19:09

millimoose