Python不逐行写入

标签 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

这可能是什么原因?

最佳答案

因为你这样做:

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

关于Python不逐行写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43038945/

相关文章:

python - 如何在python中将集合转换为列表?

python - 以 Python 2.6-/Python 3 中立的方式提示嵌套上下文管理器?

python - 如何在 PyQt4 GUI 上显示希腊字符?

python - 如何找到钻头等金属零件的确切边缘/二进制阈值?

python - 如果我必须为Python选择一个html抓取库,我应该选择哪一个

linux - 检测挂起的 linux 关闭

linux - qpdfview中没有标题栏

c++ - CPU 上的时间比实际花费的要快

python - 将函数的结果打印到 tkinter 消息框中?

python - Flask-Migrate,如果存在则不创建表