请帮我找原因,我的代码没有逐行写入文件,只写了最后一个循环。
代码 -
for root, dirs, files in os.walk(lpath):
f = open("filelist.txt","w")
for name in fnmatch.filter(files, 'hdfs-audit.log.*'):
filename = os.path.join(root, name)
bname=ntpath.basename(filename)
if os.stat(filename).st_mtime < (now - (xdays * 86400)):
print(filename)
f.write(filename)
f.write("\n")
print("file_mtime:" + str(os.stat(filename).st_mtime))
print("now:" + str(now))
print("now - xdays * 86400:" + str(now - (xdays * 86400)))
f.close()
输出 -
/var/log/hadoop/hdfs/hdfs-audit.log.2017-03-21
file_mtime:1490068800.0
now:1490592233.67
now - xdays * 86400:1490505833.67
/var/log/hadoop/hdfs/hdfs-audit.log.2017-03-20
file_mtime:1489982400.0
now:1490592233.67
now - xdays * 86400:1490505833.67
仅
/var/log/hadoop/hdfs/hdfs-audit.log.2017-03-20
/var/log/hadoop/hdfs/hdfs-audit.log.2017-03-21
这可能是什么原因?
答案 0 :(得分:4)
这是因为你这样做:
for root, dirs, files in os.walk(lpath):
f = open("filelist.txt","w")
每次循环filelist.txt
都会重新创建。因此,它已包含的所有内容都被删除了。
你需要像这样切换它:
f = open("filelist.txt","w")
for root, dirs, files in os.walk(lpath):
请记住也要将f.close()
移出循环。