gpt4 book ai didi

Python不逐行写入

转载 作者:太空宇宙 更新时间:2023-11-04 04:38:38 25 4
gpt4 key购买 nike

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

代码--

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com