[英]How to compare the modified date of two files in 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. 我正在创建一个python脚本,它将逐个访问Text文件(比如File.txt)中的每一行,然后在系统目录中搜索相应的'.py'和'.txt'文件。 For example if "COPY"(the first line) is accessed from "File.txt" then search will be done for "COPY.py" and "COPY.txt".
例如,如果从“File.txt”访问“COPY”(第一行),则将搜索“COPY.py”和“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: 我的Python代码是:
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". 我不明白为什么“COPY2”和“COPY3”正在给予“通过”。 May be I am doing it in a wrong way.
可能是我以错误的方式做这件事。 As well as on changing the comparison as "if (txttime < pytime)" in the code.
以及在代码中将比较更改为“if(txttime <pytime)” 。 All results are showing as "FAIL" in output.
所有结果在输出中显示为“FAIL”。
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. time.ctime()
将时间格式化为字符串,因此您将在文本上比较字符串"Fri Feb 08 16:34:43 2013"
和"Sat Sep 22 14:19:32 2012"
。 Just don't do that and compare the float
s that getmtime()
gives you directly: 只是不要这样做,并比较
getmtime()
直接给你的float
:
pytime = os.path.getmtime(os.path.join(root, sc))
# ...
txttime = os.path.getmtime(os.path.join(root, txt))
# ...
if (txttime > pytime):
# ...
time.ctime
返回一个字符串'Fri Feb 08 16:34:53 2013' < 'Mon Sep 24 00:50:07 2012'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.