Python 没有逐行写入

Python not writing to line by line

请帮我找出原因,我的代码没有逐行写入文件,它只写入循环的最后一个。

代码 --

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

在filelist.txt文件中,不包含

/var/log/hadoop/hdfs/hdfs-audit.log.2017-03-21

这可能是什么原因?

这是因为你这样做:

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() 移出循环。