Python没有逐行写入

时间:2017-03-27 06:03:32

标签: python linux python-2.6

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

代码 -

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

这可能是什么原因?

1 个答案:

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